检查是否存在具有特定类名的div [英] Check if div with certain class name exists

查看:170
本文介绍了检查是否存在具有特定类名的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.

这篇关于检查是否存在具有特定类名的div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆