Christopher Werby
Christopher Werby

Reputation: 910

jQuery: Select an element only when it has no class name

How can I use jQuery to select an element only if it doesn't have any classes?

I'm writing a page which allows the html author to override the default jQuery action by adding a class to the element. It should be any class at all.

So the markup might be:

<ul>
  <li class="override"></li>
  <li></li>
</ul>

I'd like jQuery to only select the second list element because it doesn't have a class.

I've looked at .hasClass(), but it seems to require a specific class name.

Thanks!

Upvotes: 15

Views: 19808

Answers (4)

filburt
filburt

Reputation: 141

You can use this:

if (!jQuery('li').hasClass('myClass') {
    do something...
}

Upvotes: 1

nnnnnn
nnnnnn

Reputation: 150010

This should do it:

$('li:not([class]),li[class=""]')

Demo: http://jsfiddle.net/aMC5X/

The first part, li:not([class]) uses the "not selector" with the "has attribute" to find any li elements that don't have the class attribute at all.

The second part, li[class=""] finds any li elements that have the attribute set to an empty string.

Upvotes: 10

Ali Demirci
Ali Demirci

Reputation: 5442

:not() Selector – jQuery API

$('li:not([class])')

Upvotes: 30

clime
clime

Reputation: 8885

This should do the thing: $('li').not('li[class]')

Upvotes: 2

Related Questions