shell
shell

Reputation: 1937

Exclude specific class name from click handler

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

Answers (3)

showdev
showdev

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

shell
shell

Reputation: 1937

I just found an answer using jquery's .not method.

http://api.jquery.com/not/

Worked for me.

Upvotes: -1

Derek
Derek

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

Related Questions