Reputation: 110083
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
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
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
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
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
Reputation: 108471
if(!$(this).attr('name')) {
$(this).attr('name', 'value');
}
that ought to do it.
Upvotes: 7