使用jQuery,我以编程方式生成了一堆div是这样的:
Some Text1
Some Text2在我的代码中的其他地方,我需要检测这些DIVs是否存在。div的类名是相同的,但每个div的ID都不同。你知道怎么用jQuery检测它们吗?
发布于 2011-04-26 05:13:49
您可以通过检查从JQuery返回的第一个对象来简化这一过程,如下所示:
if ($(".mydivclass")[0]){
// Do something if class exists
} else {
// Do something if class does not exist
}在这种情况下,如果在第一个([0])索引,然后假设类存在。
编辑2013年4月10日:我已经创建了一个jsperf测试用例here..。
发布于 2011-04-26 05:09:17
您可以使用size(),但jQuery建议您使用长度来避免另一个函数调用的开销:
$('div.mydivclass').length所以:
// since length is zero, it evaluates to false
if ($('div.mydivclass').length) {http://api.jquery.com/size/
http://api.jquery.com/length/
更新
选择的答案使用了perf测试,但它有一点缺陷,因为它还包括元素选择作为perf的一部分,这不是这里测试的内容。这是一个更新的性能测试:
http://jsperf.com/check-if-div-exists/3
我的第一次测试表明,属性检索比索引检索更快,尽管我认为它可以忽略不计。我仍然喜欢使用长度,因为对于我来说,它对于代码的意图更有意义,而不是更简洁的条件。
发布于 2015-01-21 12:27:34
没有jQuery:
原生JavaScript总是会更快。在这种情况下:(example)
if (document.querySelector('.mydivclass') !== null) {
// .. it exists
}如果要检查父元素是否包含具有特定类的另一个元素,可以使用以下任一方法。(example)
var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
// .. it exists as a child
}或者,您可以使用.contains()方法。(example)
var parent = document.querySelector('.parent'),
child = document.querySelector('.child');
if (parent.contains(child)) {
// .. it exists as a child
}..and最后,如果您想检查给定的元素是否只包含某个类,请使用:
if (el.classList.contains(className)) {
// .. el contains the class
}https://stackoverflow.com/questions/5783280
复制相似问题