使用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 ($("#myid1").hasClass("mydivclass")){// Do any thing}
其他回答
if ($("#myid1").hasClass("mydivclass")){// Do any thing}
这里是一个不使用Jquery的解决方案
var hasClass = element.classList.contains('class name to search');
// hasClass is boolean
if(hasClass === true)
{
// Class exists
}
参考链接
你可以通过检查JQuery返回的第一个对象来简化它:
if ($(".mydivclass")[0]){
// Do something if class exists
} else {
// Do something if class does not exist
}
在这种情况下,如果第一个([0])索引处有一个真值,则假设类存在。
编辑04/10/2013:我在这里创建了一个jsperf测试用例。
你可以使用size(),但jQuery建议你使用length来避免另一个函数调用的开销:
$('div.mydivclass').length
So:
// since length is zero, it evaluates to false
if ($('div.mydivclass').length) {
http://api.jquery.com/size/
http://api.jquery.com/length/
更新
选择的答案使用性能测试,但它有轻微的缺陷,因为它也包括元素选择作为性能的一部分,这不是这里要测试的内容。这是一个更新的性能测试:
http://jsperf.com/check-if-div-exists/3
我的第一次测试运行表明,属性检索比索引检索快,尽管在我看来这几乎可以忽略不计。我仍然喜欢使用长度,因为对我来说,它更有意义的意图,而不是一个更简洁的条件。
这里有一些方法:
1. if($("div").hasClass("mydivclass")){
//Your code
//It returns true if any div has 'mydivclass' name. It is a based on the class name
}
2. if($("#myid1").hasClass("mydivclass")){
//Your code
// It returns true if specific div(myid1) has this class "mydivclass" name.
// It is a based on the specific div id's.
}
3. if($("div[class='mydivclass']").length > 0){
//Your code
// It returns all the divs whose class name is "mydivclass"
// and it's length would be greater than one.
}
我们可以根据需要使用任何一种abobe定义的方法。