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

javascript add class
classlist.add not working
add class to child element javascript
javascript toggle class
how to add class dynamically in javascript
js check if elem has class
jquery add class if not exists
javascript remove class

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.

try this

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

jQuery add class .active on menu, There is no need to check if the class has already been added; .addClass will First it will remove if there is any and then add new one . Worked best for me you can use this code for adding class only when if not exist fine, because nothing happens if // there are no matching elements $("ul[class='']"). Definition and Usage The addClass () method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more class names to the class attribute. Tip: To add more than one class, separate the class names with spaces.

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

Add Class to Object on Page Load, This property is useful to add, remove and toggle CSS classes on an element. The classList property is read-only, however, you can modify it by using the add() and remove() If the specified class already exist, the class will not be added. It's important to note that this method does not replace a class. It simply adds the class, appending it to any which may already be assigned to the elements. Before jQuery version 1.12/2.2, the .addClass() method manipulated the className property of the selected elements, not the class attribute. Once the property was changed, it was the browser that updated the attribute accordingly.

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>

jQuery toggleClass() Method, The addClass() method adds one or more class names to the selected elements. This method does not remove existing class attributes, it only adds one or more Specifies a function that returns one or more class names to be added While using this site, you agree to have read and accepted our terms of use, cookie and​  The specificity of the :not pseudo class is the specificity of its argument. The :not() pseudo class does not add to the selector specificity, unlike other pseudo-classes. What I recently learned is that you can actually get burned by this matter of “argument specificity inheritance”:.foo:not(#bar) will have a specificity of 0,1,1,0.

if ($('element').hasClass('some_class')) {
   $('element').addClass('class_name');
}

add class via jquery but only when not exists, classList is a read-only property that returns a live DOMTokenList collection of the If the class attribute is not set or empty, it returns an empty  Useless selectors can be written using this pseudo-class. For example, :not(*) matches any element which is not an element, so the rule will never be applied. This pseudo-class can increase the specificity of a rule. For example, #foo:not(#bar) will match the same element as the simpler #foo, but has a higher specificity.

Are you sure you want to do it with JQuery only? You can do it with simple JavaScript

    document.getElementById("elementId").getAttribute("class")

will give you null if the class attribute is not present.

element.classList, Description: Add or remove one or more classes from each element in the set of matched already has the class, then it is removed; if an element does not have the class, then it is added. toggleClass( "bounce" ) , the <div> class is returned to the single tumble value: This signature (only!) is deprecated as of jQuery 3.0. Description: Add or remove one or more classes from each element in the set of matched elements, depending on either the class's presence or the value of the state argument. version added: 1.0.toggleClass( className )

jQuery addClass() Method, If a class name is included as a parameter, then only that class will be removeClass() method manipulated the className property of the selected elements, not the class addClass() to switch elements' classes from one to another, like so:  You can also use the Item [] property to add new elements by setting the value of a key that does not exist in the Dictionary<TKey,TValue>; for example, myCollection [myKey] = myValue (in Visual Basic, myCollection (myKey) = myValue).

Element.classList, If class already exists in the element's list of classes, it will not add the class again​. classList is only supporter in IE10 and later, also Opera Mini seems not to  yes i have used contains method but my problem is that i have used constructor of the class to add new element to the list and so even if code correctly checks whether list contains the element or not, it continuously adds the element when the page loads.. I am new to this.

.toggleClass(), Create a class in CSS and add it: <div class=". The latter should only be used if classes “can't handle it”. That limitation does not exist now, but at that time it was impossible to have a "class" property, like elem.class . Extends the container by inserting new elements, effectively increasing the container size by the number of elements inserted. Because elements in a set are unique, the insertion operation checks whether each inserted element is equivalent to an element already in the container, and if so, the element is not inserted, returning an iterator to this existing element (if the function returns a

Comments
  • Easily the best answer. No idea why there isn't more upvotes.
  • Yup far better solution +1
  • Sadly not in IE 9, if that matters to you. Source: caniuse.com/#feat=mdn-api_domtokenlist_add
  • this wont work because $(this) will not reference to $('element')
  • why not just $('element').addClass('class_name'); jquery will check the existence of the class for you
  • This doesn't solve the problem. What if the element has a class, but not the one you're interested in adding?
  • this wont work because $(this) will not reference to $(your-element)
  • Your code will actually remove class if it exists already. It will toggle it.