Reputation: 1937
How can I add a click handler to <li>
elements that don't have a certain class?
I want to do something like this:
$('ul.listClass li a :not(li.thisLi)').on("click")...
Upvotes: 0
Views: 278
Reputation: 29168
Apply :not()
to the li
part of your selector and specify the class selector you want to exclude.
$('ul.listClass li:not(.thisLi) a')
This translates to:
Select [<a>
] inside [<li>
that don't have class "thisLi"] inside [<ul>
that have class "listClass"]
For reference, see jQuery's :not() selector.
All selectors are accepted inside :not()
$('ul.listClass li:not(.thisLi) a').on("click", function() {
$(this).css({
'background-color': 'red'
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="listClass">
<li><a>Yes</a></li>
<li><a>Yes</a></li>
<li class="thisLi"><a>No</a></li>
<li><a>Yes</a></li>
<li class="thisLi"><a>No</a></li>
</ul>
Upvotes: 2
Reputation: 3435
Your :not
selector is in the wrong place, you should use it on the li.
$('ul li:not(.thisLi) a').on('click', ...);
Upvotes: 2