0

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

llanato
  • 2,508
  • 6
  • 37
  • 59
Jordan Camp
  • 842
  • 4
  • 9
  • 20

2 Answers2

1

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
1

'classList' in document.documentElement simply checks for the existence of classList within the document.documentElement Element.

From MDN's documentation on the in operator.

The in operator returns true if the specified property is in the specified object.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218