jQuery Selector only on first level not working?

236 views Asked by At

I have a simple list with a sublist

<div id="master">
<ul>
    <li><div>Trigger Me!</div></li>
    <li><div>Trigger Me!</div></li>
    <li><div>Trigger Me!</div>
        <ul>
            <li><div>Do NOT trigger me</div></li>
            <li><div>Do NOT trigger me</div></li>
        </ul>
    </li>
</ul>

I'd only like to call a function only if the user clicks on the list element on the first level, but NOT on the second. Regarding to the documentation and google, the trick should be easy by using the ">" in the selector:

$(document).ready(function(){
  $("div#master").on("click", "ul > li", function (){
    alert($(this).text());
  });
});

But as you can see on JSFiddle http://jsfiddle.net/kQH4x/ it also fires the trigger, when clicking on the sub list items.

A simular problem with the answer on stackoverflow (See here https://stackoverflow.com/a/977891/1099519 ) doesn't seem to work for some reason?

Thanks

2

There are 2 answers

0
gpgekko On BEST ANSWER

It also fires on the sublist because you don't specify which ul it should start from. The sublist has the same structure, so also qualifies for the selector.

To fix this, add the main lists parent element to the selector, so:

$(document).ready(function(){
   $("div#master").on("click", ">ul>li>div", function (){
      alert($(this).text());
   });
});

Fiddle: http://jsfiddle.net/kQH4x/6/

1
beck03076 On

Try this,

  • Don't have to use (document).ready every time.
  • Why "on", just bind "click" and read when to use "on" here
  $(function(){
       $("div#master > ul>li>div").click(function (){
          alert($(this).text());
       });
    });