jQuery: Check if div with certain class name exists

avatar picture avatar · Apr 25, 2011 · Viewed 482.4k times · Source

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?

Answer

Shaz picture Shaz · Apr 25, 2011

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.