Skip to content Skip to sidebar Skip to footer

Can't Target Specific Li Elements Using Child Selectors

I just can't figure out what I'm doing wrong. I'm trying to only select the LI elements that descend from the class(.list). Invariably, the children of the class(.sublist) are

Solution 1:

Use the direct child combinator, >, in order to only select direct children elements:

ul.list > li

But since this still selects the li that contains the .sublist element, use a combination of the :not()/:has() selectors:

$('ul.list > li:not(:has(.sublist))').on('click', function () {
    // ...
});

Example Here

$('ul.list > li:not(:has(.sublist))').on('click', function () {
    alert('working');
});
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ulclass="list"><li>One</li><liclass="special">Two</li><li>Three</li><li><ulclass="sublist"><li>1</li><li>2</li><li>3</li></ul></li></ul>

Post a Comment for "Can't Target Specific Li Elements Using Child Selectors"