css class javascript code example

Example 1: javascript add class to element

var someElement= document.getElementById("myElement");
    someElement.className += " newclass";//add "newclass" to element (space in front is important)

Example 2: element.classname javascript

let el = document.getElementById('item');

if (el.className === 'active'){
  el.className = 'inactive';
} else {
  el.className = 'active';
}

Example 3: js css class

// To add a class to an element:
const element = document.getElementById("myDIV");
element.classList.add("myClass");
// To get all classes of an element:
const element = document.getElementById("myDIV");
let classList = element.classList;

Tags:

Java Example