Kim Fierens
Kim Fierens

Reputation: 179

In jQuery, how do I apply .not to $(this) as well as other elements?

So, I have a html document with divs that have classes class1 and class2. What is the proper jQuery syntax to use if I want to apply a certain function to all divs except the one that I just clicked (i.e., $(this)) and all those with .class1 and class2? (Incidentally, $(this) need not possess either of these classes.)

I've tried various combinations, such as

$('div').not($('.class1,.class2',this)).addClass('class3');

but none seem to work.

Many thanks!

Upvotes: 0

Views: 64

Answers (2)

user7236046
user7236046

Reputation:

There's a couple of ways you can do this in jQuery. The first option is the one you're after however if you don't need to use this and hardcode in the elements directly, you can use not in CSS as well. I've included it as it's worth noting.

.not()

$("div").not(".class1").css("background-color", "red");

$("div").not(".class1").not(".class2").css("font-size", "24px");
<div class="class1">Test 1</div>

<div class="class2">Test 2</div>

<div class="class3">Test 3</div>

CodePen Example

You can use the .not() function to select an element and modify it by itself or chain them together one after the other which is what you need. You can't add this inside the parenthesis with another class because jQuery will think they're linked together and not treat them as separate rules.

:not (in jQuery)

$("li:not(:last-of-type)").css("background-color", "blue");

Another option using CSS if you don't need to use this to specify the current selector as a variable. Not ideal, but is an option.

:not (in CSS)

div:not(.orange) { color: green; }

The same as above, but again requires hard coding in the selector name. Not ideal but another option for native CSS support.

Upvotes: 1

Neil
Neil

Reputation: 14321

You can string together .not functions. Refer to the following example.

$(".clickme").click(function () {
  $('div').not('.class1, .class2').not(this).addClass('class3');
});
.class3 {
  background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class1">class1</div>
<div class="class2">class2</div>
<div>will light up</div>
<div class="clickme">Click me</div>

Upvotes: 3

Related Questions