Add a class (or attribute) if it does not already exist

How to add an attribute to an element if this element does not already have this attribute?

if (' this does not have class=selected') { $(this).addClass('selected'); } 
+4
source share
5 answers

If you are talking specifically about classes, just add it. If it already exists, it will not be added twice.

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

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

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

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

who should do it.

+5
source

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

You are probably looking for HasClass

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

 $('#mydiv').hasClass('foo') 
+2
source

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

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

Of course, as mentioned earlier, if you want to add the class in which you are checking, just add it. There is no harm.

0
source

There is no need to check and see if the class is present before adding the class. Looking through the jQuery source (https://github.com/jquery/jquery/blob/master/src/attributes.js, look for addClass ), it seems that addClass will not do anything if the class is already present, so there is no need to check first.

0
source

Source: https://habr.com/ru/post/1412084/


All Articles