JavaScript is a language full of surprises.
Every DOM element always had className property, that was nothing but white space separated list of classes. That was not the most convenient so JQuery encapsulated manipulation of that with addClass and removeClass methods.
Now, new browsers are supporting classList API, allowing JavaScript to add and remove classes from the DOM elements easily, without JQuery. This is important for mobile browsers, where everything should be parred down if possible.
So classList is a list of classes, with length property and this list of methods for manipulation:
Looks like certain browsers allows even to pass multiple classes to add, separate by space.Every DOM element always had className property, that was nothing but white space separated list of classes. That was not the most convenient so JQuery encapsulated manipulation of that with addClass and removeClass methods.
Now, new browsers are supporting classList API, allowing JavaScript to add and remove classes from the DOM elements easily, without JQuery. This is important for mobile browsers, where everything should be parred down if possible.
So classList is a list of classes, with length property and this list of methods for manipulation:
- add (class)
- contains (class)
- item (index)
- remove (class)
- toggle (class)
Of course, older IE does not support this, only IE 10 and up.
This should do for a check:
if('classList' in document.createElement('elem')) {
document.getElementById('elem').classList.add('newClass');
}
else
{
document.getElementById('elem').className += " newClass";
}