javascript - 你怎么知道一个 HTML 元素是否有一个带有纯 Javascript 的特定类?

标签 javascript html class

假设我有这个 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/

相关文章:

Javascript 对象引用链接到数组中的对象?

php 爆炸在 javascript 模板中不起作用

python - 如何通过匹配字符串在Python中提取父html标签

php - jquery 追加样式表和类函数

c# - 从 C# 类创建 SQL Server 数据库表

javascript - 更改父类

javascript - 获取对象内数组内对象的属性

html - 在 CSS 中对齐容器

javascript - 如何使用Javascript读取本地文本文件并逐行读取?

PHP访问父类变量