How to Use js to determine whether dom has a class value?
For example:
Determine whether the class of an html node has no-js.
1. jquery Implementation Method
$("html").hasClass('no-js');
Implementation of jquery source code:
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. js Implementation Method
function hasClass(element, cls) { return (' ' + element.className + ' ').indexOf(' ' + cls + ' ') > -1;}hasClass(document.querySelector("html"), 'no-js');
3. H5 classList
Note:
- The indexOf method of the string cannot distinguish classes such as. no-js and. no-js-indeed;
- The separator of the class name may not be a space or \ t.
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") ) ;
The above is all the content of this article. I hope this article will help you in your study or work. I also hope to provide more support to the customer's home!