javascript tutorial - [Solved-5 Solutions] Add a class - javascript - java script - javascript array



Problem:

How do we add a class to a given element?

Solution 1:

a element that already has a class:

<div class="someclass">
    <img ... id="image1" name="image1" />
</div>
click below button to copy the code. By JavaScript tutorial team

Solution 2:

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>
click below button to copy the code. By JavaScript tutorial team

Then

var d = document.getElementById("div1");
d.className += " otherclass";
click below button to copy the code. By JavaScript tutorial team

Solution 3:

use element.classList.add method.

var element = document.getElementById("div1");
element.classList.add("otherclass");

click below button to copy the code. By JavaScript tutorial team

Solution 4:

target element "d" however you wish and then:

d.className += ' additionalClass'; //note the space
click below button to copy the code. By JavaScript tutorial team

Solution 5:

var a = document.body;
a.classList ? a.classList.add('classname') : a.className += ' classname';
click below button to copy the code. By JavaScript tutorial team

This is shorthand for the following..

var a = document.body;
if (a.classList) {
    a.classList.add('wait');
} else {
    a.className += ' wait';
}
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Add a class