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

281

我正在使用 jQuery 动态生成一堆像这样的 div

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

我的代码中的其他地方需要检测这些DIV是否存在。这些div的类名相同,但每个div的ID都会更改。有什么想法可以使用jQuery进行检测吗?

20个回答

513
你可以通过如下方式简化此操作,即检查从JQuery返回的第一个对象:
if ($(".mydivclass")[0]){
    // Do something if class exists
} else {
    // Do something if class does not exist
}

如果在第一个索引位置([0])存在一个真值,那么就假定该类存在。

Edit 04/10/2013: 我已经创建了一个jsperf测试案例,在这里


好的观点,无论如何它只是一个属性查找。我不在乎这四个字符,但根据上下文,这可能会更加清晰... - T.J. Crowder
我最终采用了这个解决方案,虽然还有其他可行的解决方案。感谢您的快速回答。 - avatar
1
有趣的是,你可能认为在那里加上一个 :first 会提高性能(不知道 @itgorilla 是否重视性能),但它是否提高性能取决于浏览器,这可能是因为它改变了 jQuery 可以用来进行选择的本地特性。这里是一个存在 div 的测试案例这里是一个不存在 div 的测试案例 - T.J. Crowder
2
@ThomasSebastian 请尝试使用 if (!$(".mydivclass")[0]){ /* do stuff */ } - Shaz
由于jsperf链接不再有效,我在JSFiddle上创建了一个小例子:https://jsfiddle.net/cv5hd210/3/ - Userx10xC
显示剩余2条评论

140

你可以使用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-exists/3

我的第一次运行测试显示属性检索比索引检索更快,尽管我认为差别微乎其微。我仍然更喜欢使用length,因为对我来说它更符合代码意图,而不是更简洁的条件。


3
根据你提供的链接到jsperf.com上的工具显示,.length 目前提供了最佳的平均性能。 - user110857
以最小的性能影响满足我的需求进行检查的服务器。 - David O'Regan

95

没有 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() 方法。(示例)

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
}

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

5
确实,这是一种替代方案,但是价格昂贵。与早期答案中使用的方法相比,速度会变慢(在某些浏览器上明显更慢),并且内存占用也会更大(jQuery必须构建一个包含页面上所有div元素的数组,然后返回循环遍历它们以查看它们是否有该类的结果,最后将该数组丢弃)。 - T.J. Crowder
4
hasClass比这里的其他选择器快33%。 查看http://jsperf.com/hasclass00 - Hussein
1
@Hussein:只有在一个完全不现实的测试用例(两个div元素)中,才能回避我强调的问题(构建数组)。试着用一堆divs:http://jsperf.com/hasclass00/2 在我的Chrome副本上慢63%,在我的Firefox副本上慢43%,在Opera上慢98%(!)。但更重要的是,构建一个div列表然后搜索它比提供选择器引擎所需的所有信息要慢,这是有道理的。 - T.J. Crowder
1
@Hussein:请注意,我一直非常公正,并提供了平衡的反证来反驳你的说法。如果我触动了你的神经,我很抱歉,上次似乎也是这样。放松点,这不是个人冒犯,而是技术讨论。在StackOverflow上,拥有坚韧的心态和开放的思维是非常有用的。 - T.J. Crowder
1
@Hussein:HTML5的CSS选择器意味着这几乎肯定是最糟糕的方法。因为没有直接删除你的帖子,所以扣1分。 - Stefan Kendall
显示剩余24条评论

46

以下是不使用Jquery的解决方案

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

参考 链接


1
classList仅在IE10+中受支持:http://caniuse.com/classlist。您必须添加polyfill https://github.com/eligrey/classList.js或编写自己的方法。 - Andrei Drynov

25

这很简单...

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

10

为了显式地测试 div 元素:

如果( $('div.mydivclass').length ){...}


根据浏览器和jQuery版本的不同,这可能比.mydivclass稍微慢一些。 - Stefan Kendall
真的,但是OP确切地说了“jQuery - 检查是否存在具有特定类名的div”(我强调了一下),所以你得到了我的投票,因为你是第一个实际包括选择器中的div部分的人。 - T.J. Crowder

8

以下是一些方法:

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

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

7
以下是简单的代码示例:

代码如下:

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
}

7

最好的方法是如下所示检查类的长度:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接