jQuery:检查具有特定类名的div是否存在

发布于 2024-11-03 01:13:53 字数 288 浏览 3 评论 0原文

使用 jQuery,我以编程方式生成一堆 div,如下所示:

<div class="mydivclass" id="myid1">Some Text1</div>
<div class="mydivclass" id="myid2">Some Text2</div>

在代码中的其他位置,我需要检测这些 DIV 是否存在。 div 的类名相同,但每个 div 的 ID 都不同。知道如何使用 jQuery 检测它们吗?

Using jQuery I'm programmatically generating a bunch of div's like this:

<div class="mydivclass" id="myid1">Some Text1</div>
<div class="mydivclass" id="myid2">Some Text2</div>

Somewhere else in my code I need to detect if these DIVs exist. The class name for the divs is the same but the ID changes for each div. Any idea how to detect them using jQuery?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(20

神爱温柔 2024-11-10 01:13:53

您可以通过检查从 JQuery 返回的第一个对象来简化此操作,如下所示:

if ($(".mydivclass")[0]){
    // Do something if class exists
} else {
    // Do something if class does not exist
}

在这种情况下,如果第一个 ([0]) 索引处存在真值,则假设类存在。

编辑 04/10/2013: 我在此处创建了一个 jsperf 测试用例。

You can simplify this by checking the first object that is returned from JQuery like so:

if ($(".mydivclass")[0]){
    // Do something if class exists
} else {
    // Do something if class does not exist
}

In this case if there is a truthy value at the first ([0]) index, then assume class exists.

Edit 04/10/2013: I've created a jsperf test case here.

泅渡 2024-11-10 01:13:53

您可以使用 size(),但 jQuery 建议您使用 length 以避免另一个函数调用的开销:

$('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/

更新

所选答案使用性能测试,但它有一点缺陷,因为它还包括元素选择作为性能的一部分,这不是这里测试的内容。这是更新的性能测试:

http://jsperf.com/check-if-div- contains/3

我第一次运行的测试表明,属性检索比索引检索更快,尽管在我看来,它可以忽略不计。我仍然更喜欢使用长度,因为对我来说,它对于代码的意图更有意义,而不是更简洁的条件。

You can use size(), but jQuery recommends you use length to avoid the overhead of another function call:

$('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/

UPDATE

The selected answer uses a perf test, but it's slightly flawed since it is also including element selection as part of the perf, which is not what's being tested here. Here is an updated perf test:

http://jsperf.com/check-if-div-exists/3

My first run of the test shows that property retrieval is faster than index retrieval, although IMO it's pretty negligible. I still prefer using length as to me it makes more sense as to the intent of the code instead of a more terse condition.

白首有我共你 2024-11-10 01:13:53

没有 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() 父元素上的方法。 (example)

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
}

Without jQuery:

Native JavaScript is always going to be faster. In this case: (example)

if (document.querySelector('.mydivclass') !== null) {
    // .. it exists
}

If you want to check to see if a parent element contains another element with a specific class, you could use either of the following. (example)

var parent = document.querySelector('.parent');

if (parent.querySelector('.child') !== null) {
    // .. it exists as a child
}

Alternatively, you can use the .contains() method on the parent element. (example)

var parent = document.querySelector('.parent'),
    child = document.querySelector('.child');

if (parent.contains(child)) {
    // .. it exists as a child
}

..and finally, if you want to check to see if a given element merely contains a certain class, use:

if (el.classList.contains(className)) {
    // .. el contains the class
}
喜爱皱眉﹌ 2024-11-10 01:13:53
$('div').hasClass('mydivclass')// Returns true if the class exist.
$('div').hasClass('mydivclass')// Returns true if the class exist.
那伤。 2024-11-10 01:13:53

这是一个不使用 Jquery

var hasClass = element.classList.contains('class name to search');
// hasClass is boolean
if(hasClass === true)
{
     // Class exists
}

参考的解决方案链接

Here is a solution without using Jquery

var hasClass = element.classList.contains('class name to search');
// hasClass is boolean
if(hasClass === true)
{
     // Class exists
}

reference link

橪书 2024-11-10 01:13:53

这很简单...

if ($('.mydivclass').length > 0) {
  //do something
}

It's quite simple...

if ($('.mydivclass').length > 0) {
  //do something
}
卸妝后依然美 2024-11-10 01:13:53

要显式测试 div 元素:

if( $('div.mydivclass').length ){...}

To test for div elements explicitly:

if( $('div.mydivclass').length ){...}

韵柒 2024-11-10 01:13:53

这里有一些方法:

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 定义的任何一种方法。

Here are some ways:

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.
    }

We can use any one of the abobe defined ways based on the requirement.

动听の歌 2024-11-10 01:13:53

简单的代码如下:

if ($('.mydivclass').length > 0) {
   //Things to do if class exist
}

隐藏带有粒子id的div:

if ($('#'+given_id+'.mydivclass').length > 0) {
   //Things to do if class exist
}

The simple code is given below :

if ($('.mydivclass').length > 0) {
   //Things to do if class exist
}

To hide the div with particuler id :

if ($('#'+given_id+'.mydivclass').length > 0) {
   //Things to do if class exist
}
痴意少年 2024-11-10 01:13:53

最好的方法是检查课程的长度,如下所示:

if ($('.myDivClass').length) {

Best way is to check the length of the class as shown below:

if ($('.myDivClass').length) {
宛菡 2024-11-10 01:13:53
if ($("#myid1").hasClass("mydivclass")){// Do any thing}
if ($("#myid1").hasClass("mydivclass")){// Do any thing}
冰火雁神 2024-11-10 01:13:53

在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......

}

In Jquery you can use like this.

if ($(".className")[0]){

   // Do something if class exists

} else {

// Do something if class does not exist

}

With JavaScript

if (document.getElementsByClassName("className").length > 0) {

// Do something if class exists

}else{

    // Do something if class does not exist......

}
筱果果 2024-11-10 01:13:53

用它来搜索整个页面

if($('*').hasClass('mydivclass')){
// Do Stuff
}

Use this to search whole page

if($('*').hasClass('mydivclass')){
// Do Stuff
}
花间憩 2024-11-10 01:13:53

这是 Javascript 中检查类(hasClass)的非常示例解决方案:

const mydivclass = document.querySelector('.mydivclass');
// if 'hasClass' is exist on 'mydivclass'
if(mydivclass.classList.contains('hasClass')) {
   // do something if 'hasClass' is exist.
}

Here is very sample solution for check class (hasClass) in Javascript:

const mydivclass = document.querySelector('.mydivclass');
// if 'hasClass' is exist on 'mydivclass'
if(mydivclass.classList.contains('hasClass')) {
   // do something if 'hasClass' is exist.
}
南城旧梦 2024-11-10 01:13:53

检查div是否存在于某个类中

if ($(".mydivclass").length > 0) //it exists 
{

}

check if the div exists with a certain class

if ($(".mydivclass").length > 0) //it exists 
{

}
2024-11-10 01:13:53
if($(".myClass")[0] != undefined){
  // it exists
}else{
  // does not exist
}
if($(".myClass")[0] != undefined){
  // it exists
}else{
  // does not exist
}
余罪 2024-11-10 01:13:53

JavaScript 中最好的方法:

if (document.getElementsByClassName("search-box").length > 0) {
// do something
}

The best way in Javascript:

if (document.getElementsByClassName("search-box").length > 0) {
// do something
}
時窥 2024-11-10 01:13:53
if ($(".mydivclass").size()){
   // code here
}

size() 方法仅返回 jQuery 选择器选择的元素数量 - 在本例中为类 mydivclass 的元素数量。如果它返回 0,则表达式为 false,因此不存在,如果它返回任何其他数字,则 div 必须存在。

if ($(".mydivclass").size()){
   // code here
}

The size() method just returns the number of elements that the jQuery selector selects - in this case the number of elements with the class mydivclass. If it returns 0, the expression is false, and therefore there are none, and if it returns any other number, the divs must exist.

可爱暴击 2024-11-10 01:13:53
var x = document.getElementsByClassName("class name");
if (x[0]) {
alert('has');
} else {
alert('no has');
}
var x = document.getElementsByClassName("class name");
if (x[0]) {
alert('has');
} else {
alert('no has');
}
场罚期间 2024-11-10 01:13:53
jQuery(function($){
  $("#btn1").click(function(){
      if($(this).hasClass("demo")){
            alert("HAS");
      } else {
        alert("NO HAS");
      }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1" class="demo">Show Text</button>

jQuery(function($){
  $("#btn1").click(function(){
      if($(this).hasClass("demo")){
            alert("HAS");
      } else {
        alert("NO HAS");
      }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1" class="demo">Show Text</button>

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文