How to get html element's class tags

I'm using a custom modernizer config which has selected the features I employ in my page (and only those features).

So, I'd like to simply grab the className of the <html> of the page so I can check to see how many no- prefixed classes are present (maybe checking classlist.match(/no-/g).length) and determine if my javascript should just give up.

It's not clear whether I should use

document.getElementsByTagName('html').className

or

$('html').attr('class')

or

document.documentElement.className

Answers


I will go for:

document.documentElement.className;

Because doesn't involve any function's call, neither an additional layer like jquery. Ideally this one is the cleanest and the fastest.


you can use jQuery hasClass` method:

Determine whether any of the matched elements are assigned the given class.

if ( $('html').hasClass('no-something')) {
  // do something here
}

If using plain JS, the equivalent would be:

document.getElementsByTagName('html')[0].className

If you are using jquery in your project why to not use this one:

var classList = $("html").attr('class').split(/\s+/);
var prefix = 'no-';

$.each( classList, function(index, item){
  if (item.substring(0, 2) === prefix) {
    //do something
  }
});

?


Need Your Help