假设我有这个 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)
关于javascript - 你怎么知道一个 HTML 元素是否有一个带有纯 Javascript 的特定类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7908364/