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

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

问题描述:

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

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>

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

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?

你可以通过检查从JQuery返回的第一个对象来简化这个:

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
}

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

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

编辑04/10/2013:我已经创建了一个jsperf测试用例这里

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