9

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?

3

3 Answers 3

21
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)

Sign up to request clarification or add additional context in comments.

2 Comments

Since this question has been visited more than a thousand times so far, can you please update it to cover the native el.classList.contains(className); solution as is suggested by youmightnotneedjquery.com?
@AlexStack Thanks, but this is still a viable solution and is javascript only. I'd rather not replace it with a less supported method (classList is IE 10+). However you are free to post another answer as an alternative solution or edit this answer by adding it as an alternative approach (not sure which is more preferable in the context of stackoverflow's format). You should have sufficient status to edit. I believe that privilege is unlocked at 2K rep.
0

If your targets are modern browsers, you can use querySelector(). Otherwise, you can play with className property. ;)

1 Comment

Actually with a modern browser you would use .classList
0

Is somehow simple:

var elHasClass = function(element, classToTest) {
    var pattern = new RegExp("(^| )" + classToTest + "( |$)");
    return pattern.test(element.className) ? true : false;
};

Now you can do:

if( elHasClass(myEl, 'someCssClass') ) { ... do you stuff here ... }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.