说我有这个html元素

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

。现在,我通过Id选择带有javascript的元素。除纯Javascript外,我将如何等效if($('hello').hasClass('option')){//do stuff}(jQuery)?

最佳答案

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

会做的。

编辑:demo

或作为原型(prototype)函数:
HTMLElement.prototype.hasClass = function(c){
    return this.className.split(" ").indexOf(c) > -1
}


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

2015年更新:

在包括IE 10的现代浏览器中,您可以编写:
document.getElementById("hello").classList.contains("option")

请参阅引用:https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

所有主要的浏览器都支持它(引用:http://caniuse.com/#search=classlist)

10-07 18:56
查看更多