I just can't figure out what I'm doing wrong.
$('ul.list > li:not(.sublist)').click(function() { alert("working now"); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="list"> <li>One</li> <li class="special">Two</li> <li>Three</li> <li> <ul class="sublist"> <li>1</li> <li>2</li> <li>3</li> </ul> </li> </ul>
I'm trying to only select the LI elements that descend from the class(.list). Invariably, the children of the class(.sublist) are also activated when I click.Eeverything I click on gives me the alert. This is not what I want. I'm getting frustrated because I know the answer is simple but I just can't figure it out.
I've also tried using this:
$('ul.list li').not('.sublist').click(function(){
alert('working');
});
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 () {
// ...
});
$('ul.list > li:not(:has(.sublist))').on('click', function () { alert('working'); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="list"> <li>One</li> <li class="special">Two</li> <li>Three</li> <li> <ul class="sublist"> <li>1</li> <li>2</li> <li>3</li> </ul> </li> </ul>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.