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?

Kimtho6
  • 6,154
  • 9
  • 40
  • 56
chromedude
  • 4,246
  • 16
  • 65
  • 96
  • http://stackoverflow.com/questions/5085567/hasclass-with-javascript-or-site-with-jquery-to-javascript-translation – Jere Oct 26 '11 at 20:19
  • See - http://stackoverflow.com/questions/5085567/hasclass-with-javascript-or-site-with-jquery-to-javascript-translation – ipr101 Oct 26 '11 at 20:20
  • Possible duplicate of [Test if an element contains a class?](http://stackoverflow.com/questions/5898656/test-if-an-element-contains-a-class) – Teepeemm Oct 04 '15 at 00:02

3 Answers3

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

AlexStack
  • 16,766
  • 21
  • 72
  • 104
Joseph Marikle
  • 76,418
  • 17
  • 112
  • 129
  • 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 http://youmightnotneedjquery.com/? – AlexStack Feb 22 '15 at 09:04
  • @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. – Joseph Marikle Feb 23 '15 at 08:42
0

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

KorHosik
  • 1,225
  • 4
  • 14
  • 24
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 ... }
VoidMain
  • 1,987
  • 20
  • 22