0

I have this HTML structure :

<ul>
    <li class="foo">
        content1
        <ul>
            <li class="foo">
                content2
                <ul>
                    <li class="foo">
                        content3
                        <!-- N levels of depth -->
                    </li>
                </ul>
            </li>
        </ul>
    </li>
</ul>

I would like to retrieve the second <li> element (containing "content2") on a click event. I'm currently using this method :

$('body').on('click', '.foo', function() {
    var $this = $(this);
    // Do something with the element
});

However, as you can guess, this will also select the parent element as it also contains a foo class. I would like select the most "accurate" node without triggering the event for the parent element (eg: if I click on content3, it should only trigger the event for this element, not his parents).

Any suggestion ?

Simon
  • 1,679
  • 4
  • 21
  • 37
  • 1
    *"I would like to retrieve the second `
  • ` element (containing "content2") on a click event."* Always, no matter which `.foo` was clicked? I understand the second part of the question ([which is a duplicate](http://stackoverflow.com/q/1398582/218196) btw), but the first parts confuses me.
  • – Felix Kling Nov 12 '14 at 16:08
  • 1
    http://api.jquery.com/event.stoppropagation/ – j08691 Nov 12 '14 at 16:08
  • 2
    Never use `body` for delegated event handlers. Due to styling it can have a 0 calculated height and not receive bubbled mouse events! Always use `document` as your default. Much safer. – iCollect.it Ltd Nov 12 '14 at 16:15
  • 1
    @TrueBlueAussie I don't. The project is actually using more accurate selectors. I wrote `body` to remove all the project-specific stuff :) – Simon Nov 12 '14 at 16:17
  • @TrueBlueAussie: Good point, but you could say this about any other element as well. And one typically binds the handler to the closest container in the document. So, generally saying one should always bind to `document` isn't very helpful. – Felix Kling Nov 12 '14 at 16:19
  • @Felix Kling: Hence "*as your default*" (meaning if nothing closer is available). `body` is used so often I like to warn of its problems :) – iCollect.it Ltd Nov 12 '14 at 16:20
  • @TrueBlueAussie: Ok, if that is what this was implying then I agree :) – Felix Kling Nov 12 '14 at 16:21