【发布时间】:2016-05-12 14:13:36
【问题描述】:
我想检查一个元素是否指定了一个类(不知道类)。例如,给定:
<div id="ball" class="dd">
和:
<div id="ball">
我想检查它是否根本没有类。
我知道有一个名为 hasClass 的函数,但这需要类名才能工作。
编辑
该问题已在其他帖子中得到解答。 我发现最有用的答案是:
$("#mydiv").prop('classList').length
【问题讨论】:
我想检查一个元素是否指定了一个类(不知道类)。例如,给定:
<div id="ball" class="dd">
和:
<div id="ball">
我想检查它是否根本没有类。
我知道有一个名为 hasClass 的函数,但这需要类名才能工作。
该问题已在其他帖子中得到解答。 我发现最有用的答案是:
$("#mydiv").prop('classList').length
【问题讨论】:
如果你想检查元素是否有任何类,你可以使用.attr() 属性检查:
$(element).attr("class").trim().length == 0
这也处理这样的情况:
<div class=""></div>
您也可以尝试通过这种方式创建hasAttr() 函数:
var attr = $(this).attr('name');
// For some browsers, `attr` is undefined; for others, `attr` is false. Check for both.
if (typeof attr !== typeof undefined && attr !== false) {
// Element has this attribute
}
有关在A jQuery hasAttr() Equivalent 创建.hasAttr() 的更多信息。
【讨论】:
hasAttr() 之类的东西了吗?您需要使用typeof 代码来检查undefined。试试看。
一种可能的方法(如果您将具有空类的元素 - 例如 <div class=""></div> - 视为有类元素):
$('#ball').is('[class]');
比检查类属性值更直接。事实上,你甚至不需要 jQuery 来做到这一点:
document.getElementById('ball').hasAttribute('class');
另一个选项是使用classList。 This API is tremendously useful(但 IE9- 不支持)。 classList 返回DOMTokenList,一个类似数组的对象;关键是,如果类属性没有设置或者为空,那么它的长度就是0:
document.getElementById('ball').classList.length === 0;
【讨论】:
<div class=""> 可能会失败,不是吗?
true,但我认为这是OP的意图。如果不是,是的,最好将类值与空字符串进行比较,如您的答案所示。
试试这个:
<div id="ball" class="dd">
<div id="ball">
if ($('div').attr('class') != undefined){
alert('YES');
}
【讨论】:
试试这个
var attr = $(this).attr('class');
if (typeof attr !== typeof undefined && attr !== false) {
}
【讨论】: