Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to check if element has a class?

Tags:

javascript

dom

The problem

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.

Example

// 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

like image 763
Adam Halasz Avatar asked Jun 09 '12 11:06

Adam Halasz


People also ask

How do you know if an element does not have a class?

Use the classList. contains() method to check if an element does not have a specific class, e.g. if (! el. classList.

How do you check if an element contains a class in jQuery?

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".

Can a element have class?

HTML elements can have an id and/or class attribute.

How do I check if a div contains an element?

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.


2 Answers

function hasClass( elem, klass ) {
     return (" " + elem.className + " " ).indexOf( " "+klass+" " ) > -1;
}
like image 51
Esailija Avatar answered Oct 17 '22 06:10

Esailija


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.

like image 23
ZER0 Avatar answered Oct 17 '22 07:10

ZER0