3

Selecting elements by classnames is easy. But, is it possible to select any DOM-element who has no class set at all in jQuery? Kind of empty-style-selector.

Example:

<div class="nope">
     <div>You need me!</div>
</div>
<span class="foo">Not me</span>

var answer = $("selector-im-looking-for").text(); // You need me!
Andries
  • 1,547
  • 10
  • 29

4 Answers4

4

I'd suggest:

$('div').not('[class]');

JS Fiddle demo, note that this approach fails to select the <span> element ( pertinent HTML below).

Or, to select all elements without a class attribute:

$('body *:not("[class]")')

JS Fiddle demo, note that this also fails to select the <span> element.

The universal selector (*) is implied in the case of a pseudo-class selector being used without a tag-name, but in the event it's used I prefer to be explicit about it, though it is optional in this context.

Further, to select all elements, within the <body>, with either no class attribute, or with a class attribute, but no set class-name:

$('body *').filter(function(){
    return !this.className || !this.className.length;
})

JS Fiddle demo, this approach, because it tests for both the absence of a className property as well as an empty/zero-length className property, successfully finds the <span>.

The above demos were all used with the following HTML:

<div class="nope">
    Some text that should not be selected.
     <div>You need me!</div>
</div>
<span class="foo">Not me</span>
<span class="">Me too (probably)</span>

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
3

Are you expecting the following?

var answer = $("div").text(); // You need me!

Or

var answer = $(":not(.nope)").text(); // You need me!

Edit following clarification:

Like this?

var answer = $('div:not([class])');
Pez Cuckow
  • 14,048
  • 16
  • 80
  • 130
1

try something like this

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

REFERENCE

http://www.w3.org/TR/css3-selectors/#negation

jQuery get all divs which do not have class attribute

Community
  • 1
  • 1
rajesh kakawat
  • 10,826
  • 1
  • 21
  • 40
1

you can use filter,

$('div').filter(function(){
    return $(this).attr('class') === null;
}).each(function(){
    //iterate item
})
David Thomas
  • 249,100
  • 51
  • 377
  • 410
jrey
  • 2,163
  • 1
  • 32
  • 48
  • 1
    I hope I've caused you no offense, but I chose to format your answer (in order to present the code *as code*, and for readability). For formatting help (to help you format code as code) please have a look at the [Markdown help page](http://stackoverflow.com/editing-help/). :) – David Thomas Jan 14 '14 at 12:52