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.
To add a class to an element, without removing/affecting existing values, append a space and the new classname, like so: document. getElementById("MyElement").
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.
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
try this
var elem = $('selector');
if(!elem.hasClass('desired_class')){
elem.addClass('desired_class');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With