symdesign
2/4/2016 - 6:40 PM

Add class to HTML Element

Adding a class to an element the easy way. Note that IE9 needs a polyfill (https://gist.github.com/devongovett/1381839) and there are some restrictions for SVGs.

// div is an object reference to a <div> element with class="foo bar"
div.classList.remove("foo");
div.classList.add("anotherclass");

// if visible is set remove it, otherwise add it
div.classList.toggle("visible");

//  add/remove visible, depending on test conditional, i less than 10
div.classList.toggle("visible", i < 10 );

console.log(div.classList.contains("foo"));

div.classList.add("foo","bar"); //add multiple classes