Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you find out if an HTML element has a certain class with plain Javascript?

Say I have this html element

<div id="hello" class="hello option john">Hello</div>
<div id="hello" class="hello john">Hello</div>

. Now I select the element with javascript by it's Id. How would I do an equivalent of if($('hello').hasClass('option')){//do stuff}(jQuery) except in plain Javascript?

like image 281
chromedude Avatar asked Oct 26 '11 20:10

chromedude


People also ask

How do you check if an element doesn't have a class in JavaScript?

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

How do you find the class in HTML?

Open the page in a browser, like Chrome or Firefox, right click and inspect the element, You should see the source, there you can see the class.

Can you get element by class in JavaScript?

The JavaScript getElementsByClassName is used to get all the elements that belong to a particular class. When the JavaScript get element by class name method is called on the document object, it searches the complete document, including the root nodes, and returns an array containing all the elements.


1 Answers

if(document.getElementById("hello").className.split(" ").indexOf("option") > -1);

That'll do it.

EDIT: demo

or as a prototyped function:

HTMLElement.prototype.hasClass = function(c){
    return this.className.split(" ").indexOf(c) > -1
}

and

document.getElementById("hello").hasClass("option")

Update 2015:

In modern browsers including IE 10 you can write:

document.getElementById("hello").classList.contains("option")

See the reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

It's supported in all major browsers (ref: http://caniuse.com/#search=classlist)

like image 52
Joseph Marikle Avatar answered Sep 22 '22 15:09

Joseph Marikle