js add class to html code example
Example 1: js add class
var element = document.getElementById('element');
element.classList.add('class-1');
element.classList.add('class-2', 'class-3');
element.classList.remove('class-3');
Example 2: javascript add class
var myElement = document.querySelector('#myElement');
myElement.classList.add('some-class');
myElement.classList.add('one-class', 'one-more-class');
myElement.classList.remove('any-class');
Example 3: js add class
const div = document.createElement('div');
div.className = 'foo';
console.log(div.outerHTML);
div.classList.remove("foo");
div.classList.add("anotherclass");
console.log(div.outerHTML);
div.classList.toggle("visible");
div.classList.toggle("visible", i < 10 );
console.log(div.classList.contains("foo"));
div.classList.add("foo", "bar", "baz");
div.classList.remove("foo", "bar", "baz");
const cls = ["foo", "bar"];
div.classList.add(...cls);
div.classList.remove(...cls);
div.classList.replace("foo", "bar");
Example 4: javascript add class to element
var someElement= document.getElementById("myElement");
someElement.className += " newclass";
Example 5: add class to html tag javascript
var root = document.getElementsByTagName( 'html' )[0];
root.className += ' responsive';