If the element has multiple classes then it will not match with the regular property value checking, so I'm looking for the best way to check if the object has a particular class in the element's className property.
// element's classname is 'hello world helloworld'
var element = document.getElementById('element');
// this obviously fails
if(element.className == 'hello'){ ... }
// this is not good if the className is just 'helloworld' because it will match
if(element.className.indexOf('hello') != -1){ ... }
So what would be the best way to do this?
just pure javascript please
Use the classList. contains() method to check if an element does not have a specific class, e.g. if (! el. classList.
jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".
HTML elements can have an id and/or class attribute.
To check if a div element contains specific text:Use the includes() method to check if the specific text is contained in the div . If it is, the includes() method returns true , otherwise false is returned.
function hasClass( elem, klass ) {
return (" " + elem.className + " " ).indexOf( " "+klass+" " ) > -1;
}
In modern browsers, you can use classList:
if (element.classList.contains("hello")) {
// do something
}
In the browser that doesn't implement classList
but exposes the DOM's prototype, you can use the shim showed in the link.
Otherwise, you can use the same shim's code to have a generic function without manipulate the prototype.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With