Java Reference
In-Depth Information
The
toggle
method is a particularly useful method that will
add
a class if an element
doesn't have it already and
remove
the class if it does have it. It returns
true
if the class
was added and
false
if it was removed. For example:
swim.classList.toggle('sport'); // will remove the 'sport'
class
<< false
swimm.classList.toggle('sport'); // will add the 'sport'
class back
<< true
The
contains
method will check to see if an element has a particular class:
swim.classList.contains('sport');
<< true
swim.classList.toggle('sport');
<< false
swim.classList.contains('sport');
<< false
Note: Adding Classes in Old Versions of Internet
Explorer
Unfortunately, the
classlist
property is only available in Internet Ex-
plorer version 10 and above, so if you want to support older versions of In-
ternet Explorer, you could create a function that will add an extra class to
an element, rather than just replace the current class. The
addClass
func-
tion takes the element and the new class name to be added as parameters. It
uses a simple
if
block to check if the value of the
className
property
is truthy. If it is, it will append the new class to the end of the current class;
otherwise, it will simply set the new class as the element's class:
function addClass(element,newClass){
if (element.className) {
