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

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


I wrote a JavaScript-only function that checks if the class exists before adding it to the element. (You can always use classList as mentioned here, but support for that starts with IE10.)

function addClass(name, element) {
  var classesString;
  classesString = element.className || "";
  if (classesString.indexOf(name) === -1) {
    element.className += " " + name;
  }
}

var element = document.getElementById('some-element');

addClass("on", element); // Adds the class 'on'
addClass("on", element); // Ignored
addClass("on", element); // Ignored

document.write('Element classes: ' + element.className);
<div id="some-element"></div>

try this

var elem = $('selector');
if(!elem.hasClass('desired_class')){
  elem.addClass('desired_class');
 }

In plain javascript check class existence by using below code. Here I'm checking el (element) has tempClass or not

var el = document.getElementById("div1");

...

if (el.classList.contains("tempClass")){
   return true;
}