javascript – How to select element in the lowest hierarchical level?

Question:

I need to select the parent ul of the li element that is being clicked. However, as one li is inside the other, javascript understands that I'm clicking on the li and on all the li countries.

<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 thousands of ways to make the ul selection, but I ended up deleting the code and I was only left with a small "debug" code:

$(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 see that the js understands that I clicked on the entire hierarchy of the li and not just on the clicked one, even with this.

Answer:

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

event.stopPropagation();

Your code should look similar to:

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

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

Scroll to Top