Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add class to element only if it already does not have it?

How to add a class to an element only if it already does not have it? Say we don't know if the element has class="desired_class ... but we want to make sure it has.

like image 848
myWallJSON Avatar asked Mar 01 '12 11:03

myWallJSON


People also ask

How do you add classes to elements?

To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so: document. getElementById("MyElement").

Can you add a class to the HTML element?

To add a class to an element rather than replacing its existing classes, use the += operator instead. Note, it is important to prefix the new classname with space; otherwise, one of the existing classes of an element is lost.


2 Answers

Also, you can use classList property and it's add() method:

var element = document.getElementById('myElement');
element.classList.add('myClass');

The class name will be added only if the element does not have it.

More about classList: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

like image 135
arnisritins Avatar answered Oct 06 '22 00:10

arnisritins


try this

var elem = $('selector');
if(!elem.hasClass('desired_class')){
  elem.addClass('desired_class');
 }
like image 29
dku.rajkumar Avatar answered Oct 05 '22 23:10

dku.rajkumar