How to select element in the lowest hierarchical level?

Asked

Viewed 991 times

9

I need to select the ul parent of the element li that is being clicked. But as a li is inside the other javascript understands that I am clicking on li and in all li parents.

<ul class="lista">
    <li class="item">
        Pai
        <ul class="lista">
            <li class="item">
                Filho
                <ul class="lista">
                    <li class="item">Neto 1</li>
                    <li class="item">Neto 2</li>
                </ul>
            </li>
        <ul>
    </li>
</ul>

I’ve tried a thousand ways to select ul, but I ended up erasing the code and I only had a small code of "debug":

$(document).ready(function () {
    $(document).on('click','.item:last-child', function () {
         alert($(this).parent().length);
    });
});

It was only when I made this code that I was able to visualize q js understands that I clicked on the entire hierarchy of li and not only on the clicked one, even with this.

2 answers

12

Try to use it like this:

$(document).ready(function () {
    $(document).on('click','.item', function (e) { // retirei o :last-child
        e.stopPropagation(); // impedir a propagaço do evento pelos li's
         console.log($(this).parent()); // também pode usar .closest('ul')
    });
});

Example

Note that in your HTML one of <ul> do not have the correct closure:

        <ul>  // aqui devia ser </ul>
    </li>
</ul>

You can read more here about the Event.stopPropagation(), but in the background prevents the clicked event to propagate in the DOM tree and be fired in other elements.

The :last-child I had to stop tying the event to Neto 1, therefore the Filho was appearing instead of expected.

12


What is happening is that the event (in this case, the click) continues to propagate through the "parents" elements of the clicked li. To prevent the event from spreading, you must use the function:

event.stopPropagation();

Your code should look like:

$(document).ready(function () {
    $(document).on('click','.item', function (event) {
       event.stopPropagation(); 
       alert($(this).parent().length);
    });
});

Note that I also removed the pseudo-selector :last-Child. This selector is used to always choose the last child element of the parent element - that is, the event would only be triggered when the person clicked on the last element of the list.

  • 1

    I marked it correctly by the :last-Child detail. The first answer only corrected this later. I used this in my test: http://doforneiro.com.br/lista1.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.