Alex Rivera | Logout

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

Asked 2011-10-26T20:17:20.397
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?

Edit
Report

1 Answer

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 ... }
answered 2011-10-26T20:23:38.367

Your Answer