使用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) {
其他回答
Javascript中最好的方法:
if (document.getElementsByClassName("search-box").length > 0) {
// do something
}
这很简单……
if ($('.mydivclass').length > 0) {
//do something
}
这里有一些方法:
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定义的方法。
下面是Javascript中检查类(hasClass)的示例解决方案:
const mydivclass = document.querySelector('.mydivclass');
// if 'hasClass' is exist on 'mydivclass'
if(mydivclass.classList.contains('hasClass')) {
// do something if 'hasClass' is exist.
}
在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......
}