Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a class to a given element?

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?

like image 389
Blankman Avatar asked Feb 03 '09 13:02

Blankman


People also ask

How do I add a class to an element in HTML?

HTML. Using . add() method: This method is used to add a class name to the selected element.

How do I add a class to an element in CSS?

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.


2 Answers

If you're only targeting modern browsers:

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"); 

If you need to support Internet Explorer 9 or lower:

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.

like image 168
Ishmael Avatar answered Sep 25 '22 15:09

Ishmael


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.

like image 23
Yuri Avatar answered Sep 22 '22 15:09

Yuri