[英]How do you find out if an HTML element has a certain class with plain Javascript?
Say I have this html element 说我有这个html元素
<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.
现在我通过它的Id选择带有javascript的元素。 How would I do an equivalent of
if($('hello').hasClass('option')){//do stuff}
(jQuery) except in plain Javascript? 除了简单的Javascript之外,我如何做一个等效的
if($('hello').hasClass('option')){//do stuff}
(jQuery)?
if(document.getElementById("hello").className.split(" ").indexOf("option") > -1);
That'll do it. 那就行了。
or as a prototyped function: 或作为原型功能:
HTMLElement.prototype.hasClass = function(c){
return this.className.split(" ").indexOf(c) > -1
}
and 和
document.getElementById("hello").hasClass("option")
In modern browsers including IE 10 you can write: 在包括IE 10的现代浏览器中,您可以编写:
document.getElementById("hello").classList.contains("option")
See the reference: https://developer.mozilla.org/en-US/docs/Web/API/Element/classList 参见参考: https : //developer.mozilla.org/en-US/docs/Web/API/Element/classList
It's supported in all major browsers (ref: http://caniuse.com/#search=classlist ) 所有主流浏览器都支持它(参考: http : //caniuse.com/#search=classlist )
If your targets are modern browsers, you can use querySelector() . 如果您的目标是现代浏览器,则可以使用querySelector() 。 Otherwise, you can play with className property.
否则,您可以使用className属性。 ;)
;)
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 ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.