Select elements without any class [duplicate]

I need to find, via jQuery selectors, all spans in a page that have no class.

Example:

<span class='Cool'>do not found me</span>
<span>me, me, take me please!!!</span>

Use :not() and the attribute not selector [att!=val] to filter out elements with a non-empty class attribute:

$('span:not([class!=""])')

jsFiddle preview

Note however that [att!=val] is a non-standard jQuery selector, which means the selector cannot be used in CSS or with document.querySelectorAll(). If you're like me, and you're a stickler for following the standards and so want to eschew non-standard jQuery selectors where possible, the following is a direct equivalent:

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

This matches

  • span elements that have no class attribute, and
  • span elements that do have a class attribute, but only when the attribute value is empty.

In most cases, though, you should be able to get away with just the first portion:

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

You'll usually only find empty class attributes in markup generated by the application that's responsible for outputting it, or by developers who aren't paying attention.


See this answer to do it with css only Can I write a CSS selector selecting elements NOT having a certain class?

:not([class])

Actually, this will select anything witch do not have a .class applied to it.

I gathered a jsfiddle demo

html

<h2 class="fake-class">fake-class will be green</h2>
<h2 class="">empty class SHOULD be white</h2>
<h2>no class should be red</h2>
<h2 class="fake-clas2s">fake-class2 SHOULD be white</h2>
<h2 class="">empty class2 SHOULD be white</h2>
<h2>no class2 SHOULD be red</h2>

css

h2 {color:#fff}
:not([class]) {color:red;background-color:blue}
.fake-class {color:green}