chr*_*ude 5 html javascript class
说我有这个html元素
<div id="hello" class="hello option john">Hello</div>
<div id="hello" class="hello john">Hello</div>
Run Code Online (Sandbox Code Playgroud)
.现在我通过它的Id选择带有javascript的元素.if($('hello').hasClass('option')){//do stuff}除了简单的Javascript之外,我将如何做(jQuery)等效的?
Jos*_*kle 14
if(document.getElementById("hello").className.split(" ").indexOf("option") > -1);
Run Code Online (Sandbox Code Playgroud)
那就行了.
或作为原型功能:
HTMLElement.prototype.hasClass = function(c){
return this.className.split(" ").indexOf(c) > -1
}
Run Code Online (Sandbox Code Playgroud)
和
document.getElementById("hello").hasClass("option")
Run Code Online (Sandbox Code Playgroud)
在包括IE 10的现代浏览器中,您可以编写:
document.getElementById("hello").classList.contains("option")
Run Code Online (Sandbox Code Playgroud)
参见参考:https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
所有主流浏览器都支持它(参考:http://caniuse.com/#search=classlist)