David542
David542

Reputation: 110083

Add a class (or attribute) if not already there

How would I add an attribute to an element if that element does not already have that attribute?

if (' this does not have class=selected') {

    $(this).addClass('selected');
}

Upvotes: 4

Views: 4841

Answers (5)

Ethan Brown
Ethan Brown

Reputation: 27282

It is not necessary to check and see if the class is already present before adding the class. Looking through the jQuery source (https://github.com/jquery/jquery/blob/master/src/attributes.js, search for addClass), it appears that addClass will do nothing if the class is already present. Therefore, there's no point to checking first.

Upvotes: 0

kfirbreger
kfirbreger

Reputation: 109

You can use the attribute not selector. This works not only for classes but for any attribute

if($('#elemid[class!="myclass"]').length) {
    $('#elemid').addClass('otherClass');
}

Of course as mentioned before if you want to add the class your checking against, just add it. There is no harm in that.

Upvotes: 1

cliffs of insanity
cliffs of insanity

Reputation: 3694

If you're talking specifically about classes, then just go ahead and add it. If it already exists, it won't be added twice.

$(this).addClass('selected'); // will only add the class if it doesn't exist

I doubt that first testing for the class would be any more efficient.

live demo: http://jsfiddle.net/2sLd5/

Upvotes: 3

turtlepick
turtlepick

Reputation: 2714

The jQuery documentation is your friend! :) http://api.jquery.com/category/css/

You are probably looking for the HasClass

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

$('#mydiv').hasClass('foo')

Upvotes: 2

Ben Lesh
Ben Lesh

Reputation: 108471

if(!$(this).attr('name')) {
   $(this).attr('name', 'value');
}

that ought to do it.

Upvotes: 7

Related Questions