简体   繁体   中英

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?

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 )

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM