How to select element at the lowest hierarchical level?

8

I need to select the ul parent of the li element being clicked. But as a li stays within the other the javascript understands that I am clicking on li and all li pais.

<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 already tried a thousand ways to make the selection of ul , but I ended up deleting the code and I just got a little debug code:

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

Only when I made this code I was able to see that js understands that I clicked on all the hierarchies of the li and not only on the clicked, even with this.

    
asked by anonymous 28.02.2014 / 20:18

2 answers

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 clicks on the last element of the list.

    
28.02.2014 / 20:32
12

Try using 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 the <ul> does not have the correct closing:

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

You can read more here about event.stopPropagation () , but in the background it prevents the click event from propagating in the DOM tree and being triggered on other elements.

The :last-child it had was preventing tethering the event to Neto 1 , so Filho was appearing rather than expected.

    
28.02.2014 / 20:23