使用jQuery,我以编程方式生成了一堆div,就像这样:
<div class="mydivclass" id="myid1">Some Text1</div>
<div class="mydivclass" id="myid2">Some Text2</div>
在代码的其他地方,我需要检测这些div是否存在。div的类名是相同的,但ID为每个div的变化。任何想法如何检测他们使用jQuery?
使用jQuery,我以编程方式生成了一堆div,就像这样:
<div class="mydivclass" id="myid1">Some Text1</div>
<div class="mydivclass" id="myid2">Some Text2</div>
在代码的其他地方,我需要检测这些div是否存在。div的类名是相同的,但ID为每个div的变化。任何想法如何检测他们使用jQuery?
当前回答
if($(".myClass")[0] != undefined){
// it exists
}else{
// does not exist
}
其他回答
$('div').hasClass('mydivclass')// Returns true if the class exist.
你可以通过检查JQuery返回的第一个对象来简化它:
if ($(".mydivclass")[0]){
// Do something if class exists
} else {
// Do something if class does not exist
}
在这种情况下,如果第一个([0])索引处有一个真值,则假设类存在。
编辑04/10/2013:我在这里创建了一个jsperf测试用例。
Javascript中最好的方法:
if (document.getElementsByClassName("search-box").length > 0) {
// do something
}
要显式地测试div元素:
如果($ (' div.mydivclass”)。长度){…}
没有jQuery:
原生JavaScript总是更快。在这种情况下:(示例)
if (document.querySelector('.mydivclass') !== null) {
// .. it exists
}
如果希望检查父元素是否包含具有特定类的另一个元素,可以使用以下方法之一。(例子)
var parent = document.querySelector('.parent');
if (parent.querySelector('.child') !== null) {
// .. it exists as a child
}
或者,您可以在父元素上使用.contains()方法。(例子)
var parent = document.querySelector('.parent'),
child = document.querySelector('.child');
if (parent.contains(child)) {
// .. it exists as a child
}
..最后,如果你想检查一个给定的元素是否只包含一个特定的类,使用:
if (el.classList.contains(className)) {
// .. el contains the class
}