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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5783280/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:48:56  来源:igfitidea点击:

jQuery: Check if div with certain class name exists

javascriptjqueryjquery-selectorsjavascript-framework

提问by avatar

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

使用 jQuery 我以编程方式生成一堆这样的div's:

<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?

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

回答by Shaz

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

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

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.

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

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

2013 年 4 月10 日编辑:我在这里创建了一个 jsperf 测试用例。

回答by Eli

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

您可以使用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/size/

http://api.jquery.com/length/

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

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.

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

回答by Josh Crozier

Without jQuery:

没有 jQuery:

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

原生 JavaScript 总是会更快。在这种情况下:(示例)

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)

或者,您可以.contains()在父元素上使用该方法。(例子)

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
}

回答by Hussein

$('div').hasClass('mydivclass')// Returns true if the class exist.

回答by Ronald

Here is a solution without using Jquery

这是不使用Jquery的解决方案

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

reference link

参考链接

回答by methodofaction

It's quite simple...

这很简单...

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

回答by Stefan Kendall

To test for divelements explicitly:

div显式测试元素:

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

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

回答by Jitendra Damor

The simple code is given below :

简单的代码如下:

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

To hide the div with particuler id :

要隐藏带有 particuler id 的 div:

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

回答by Sheo Dayal Singh

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.

我们可以根据需求使用任何一种 abobe 定义的方式。

回答by stairie

if($(".myClass")[0] != undefined){
  // it exists
}else{
  // does not exist
}