使用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 ($('.myDivClass').length) {
其他回答
在Jquery中,你可以这样使用。
if ($(".className")[0]){
// Do something if class exists
} else {
// Do something if class does not exist
}
使用JavaScript
if (document.getElementsByClassName("className").length > 0) {
// Do something if class exists
}else{
// Do something if class does not exist......
}
这里是一个不使用Jquery的解决方案
var hasClass = element.classList.contains('class name to search');
// hasClass is boolean
if(hasClass === true)
{
// Class exists
}
参考链接
要显式地测试div元素:
如果($ (' div.mydivclass”)。长度){…}
Javascript中最好的方法:
if (document.getElementsByClassName("search-box").length > 0) {
// do something
}
检查div是否与某个类一起存在
if ($(".mydivclass").length > 0) //it exists
{
}