Youss
Youss

Reputation: 4212

How to write "if not class" jQuery selector?

I want to do something with var p:

var p = $("li:last");

But I don't want to do anything if there is a certain Class appended. I tried :not like this:

var p = $("li:last:not(.Class)");

This doesn't work. How can I exclude .Class in my var?

Upvotes: 38

Views: 71979

Answers (3)

osdamv
osdamv

Reputation: 3583

var p = $("li:last");
if (!p.hasClass('Class')){
//some stuff
}

http://api.jquery.com/hasClass/

Upvotes: 2

cambraca
cambraca

Reputation: 27839

Actually :not does work as a selector.

If you want to select the last element that doesn't have the class, use this

var p = $("li:not(.Class):last");

This selects first the lis that don't have that class, and then the last of them. See it working here.

To make it perfectly clear, these are equivalent:

var p = $("li:not(.Class):last");
var p = $("li").not(".Class").last();

And, also, these are equivalent:

var p = $("li:last:not(.Class)");
var p = $("li").last().not(".Class");

Upvotes: 15

bhamlin
bhamlin

Reputation: 5187

var p = $("li:last").not(".Class");

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

Upvotes: 50

Related Questions