Saa
Saa

Reputation: 63

How to find elements without a class in Jquery?

I have the following html

<div class="one">One<div>
<div class="two">two<div>
<div >three<div>
<div >four<div>
<div class="three">five<div>

How would I find the div elements which don't have a class attribute? ie three and four?

Upvotes: 4

Views: 2211

Answers (6)

Sarath
Sarath

Reputation: 9146

Use :not selector to filter

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

Upvotes: 4

Arun P Johny
Arun P Johny

Reputation: 388316

Another option is to use .not() with Has Attribute Selector

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

Upvotes: 2

Suresh Atta
Suresh Atta

Reputation: 121998

You can use :not selector

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

here is API

And a simple Fiddle

Upvotes: 10

James Donnelly
James Donnelly

Reputation: 128781

Assuming you're not wanting to select all the dividers which have no classes, you can use nth-child to select specific ones if you know exactly where they are within a container. This will select your class-less dividers:

$('div:nth-child(3)') // Selects the third divider
$('div:nth-child(4)') // Selects the fourth divider
$('div:nth-child(3), div:nth-child(4)') // Selects both

JSFiddle example.

Alternatively you can select using .prev() and .next():

$('div.two').next() // Selects the divider after div class="two"
$('div.three').prev() // Selects the divider before div class="three"

Upvotes: 0

Michael Aaron Safyan
Michael Aaron Safyan

Reputation: 95479

There are different ways to do it. You could use .children() to get the list and then index into that. Or you could look up the second element and use .next() to get its sibling.

Upvotes: 0

alex
alex

Reputation: 490153

Combine the :not() selector with the attribute present selector [class].

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

jsFiddle.

Upvotes: 3

Related Questions