Hello all I'm working through an example of a slide and push menu on another site and am struggling to understand an if statement in the classie.js file that is included with the source download.
if ( 'classList' in document.documentElement ) {
hasClass = function( elem, c ) {
return elem.classList.contains( c );
};
addClass = function( elem, c ) {
elem.classList.add( c );
};
removeClass = function( elem, c ) {
elem.classList.remove( c );
};
}
else {
hasClass = function( elem, c ) {
return classReg( c ).test( elem.className );
};
addClass = function( elem, c ) {
if ( !hasClass( elem, c ) ) {
elem.className = elem.className + ' ' + c;
}
};
removeClass = function( elem, c ) {
elem.className = elem.className.replace( classReg( c ), ' ' );
};
}
I can't seem to wrap my head around the first IF statement. My understanding is that document.documentElement
returns the <html>
tag, but what is that 'classList'
business? The only thing I can find on it was on mdn, but I don't understand at all what that IF statement is testing for. Any help would be appreciated. Thanks
Newer browsers support a .classList
property on DOM element nodes. It's an array of class names. Older browsers just support the .className
property, which is a single string containing space-separated class names.
If the if
statement in the code you posted sees that the document node has a .classList
property, it knows that it's running on a newer browser. If not, then it creates alternative versions of some class management utilities.