How to use js to judge whether dom has a value of class

  • 2021-07-21 05:40:22
  • OfStack

For example:


<html class="no-js">
<head>
</head>
<body>
</body>
</html>

It is judged whether the class of the html node has no-js.

1. Implementation of jquery

$("html").hasClass('no-js');

jquery source code implementation:


var rclass = /[\t\r\n\f]/g;
jQuery.fn.extend({
 hasClass: function(selector) {
  var className = " " + selector + " ",
   i = 0,
   l = this.length;
  for (; i < l; i++) {
   if (this[i].nodeType === 1 &&
    (" " + this[i].className + " ").replace(rclass, " ").indexOf(className) > -1) {
    return true;
   }
  }
  return false;
 }
})

2. Implementation of js


function hasClass(element, cls) {
 return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;
}
hasClass(document.querySelector("html"), 'no-js');

3. classList for H5

Under the description:

The indexOf method of a string is indistinguishable from classes like. no-js and. no-js-indeed; The separator of the class name may not be a space, or it may be\ t, etc.

Code:


var hasClass = (function(){
 var div = document.createElement("div") ;
 if( "classList" in div && typeof div.classList.contains === "function" ) {
  return function(elem, className){
   return elem.classList.contains(className) ;
  } ;
 } else {
  return function(elem, className){
   var classes = elem.className.split(/\s+/) ;
   for(var i= 0 ; i < classes.length ; i ++) {
    if( classes[i] === className ) {
     return true ;
    }
   }
   return false ;
  } ;
 }
})() ;
alert( hasClass(document.documentElement, "no-js") ) ;

Related articles: