I have an element that already has a class:
<div class="someclass"> <img ... id="image1" name="image1" /> </div>
Now, I want to create a JavaScript function that will add a class to the div
(not replace, but add).
How can I do that?
HTML. Using . add() method: This method is used to add a class name to the selected element.
If you want to use a class, use a full stop (.) followed by the class name in a style block. Next, use a bracket called a declaration block that contains the property to stylize the element, such as text color or text size. CSS Classes will help you stylize HTML elements quickly.
Use element.classList.add to add a class:
element.classList.add("my-class");
And element.classList.remove to remove a class:
element.classList.remove("my-class");
Add a space plus the name of your new class to the className
property of the element. First, put an id
on the element so you can easily get a reference.
<div id="div1" class="someclass"> <img ... id="image1" name="image1" /> </div>
Then
var d = document.getElementById("div1"); d.className += " otherclass";
Note the space before otherclass
. It's important to include the space otherwise it compromises existing classes that come before it in the class list.
See also element.className on MDN.
The easiest way to do this without any framework is to use element.classList.add method.
var element = document.getElementById("div1"); element.classList.add("otherclass");
Edit: And if you want to remove class from an element -
element.classList.remove("otherclass");
I prefer not having to add any empty space and duplicate entry handling myself (which is required when using the document.className
approach). There are some browser limitations, but you can work around them using polyfills.
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