jQuery document.on() child selector

I have a ul and i want create an alert when i click on a child li.

<ul id="myul">
    <div class="test">
        <div class="test1">
            <li></li>
            <li></li>
        </div>
    </div>
</ul>

Something like that is possible:

$(document).on('click', '#myul.find(li)', function()
{
   alert('hey!');
}

I can't use #myul > li because I have other child before li.

Answers:

Answer

You can use

$(document).on('click','#myul li', eventHandler) 

which means you're registering an event handler on the document but eventHandler will be invoked only when the event originated from #myul li i.e for any li child of myul, not just the immediate child, can be a descendant as well which fits your case.

But I suggest that you even reduce the scope of the event registration to the closest ancestor of li like below.

$('#myul').on('click','li', eventHandler)
Answer

ul elements can only contain li elements eventually mixed with ol and ul elements. You can can fix your html and jquery to be like:

$(document).on('click', '#myul ul li', function() {
  alert('hey!');
});
ul,
li {
  list-style-type: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myul">
  <li class="test">
    <ul class="test1">
      <li>rasd</li>
      <li>sadsad</li>
    </ul>
  </li>
</ul>

Answer

You can use simply css child selector as below mentioned. It will apply direct children not just any descendant.

Note: As per http://w3.org standards you can't make the div direct children of ul. The div tag should come inside the li's.

jQuery("#myul > li").click(function(){

    alert('hey!');

});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.