jQuery: Check if div with certain class name exists

jQuery: Check if div with certain class name exists

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

Some Text1
Some Text2

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?


Solution 1:

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.

Solution 2:

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



// since length is zero, it evaluates to false
if ($('div.mydivclass').length) {


Related:  Iterating with while loop instead of for loop



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:


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.

Solution 3:

Without jQuery:

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

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)

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

Solution 4:

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

Solution 5:

Here is a solution without using Jquery

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

reference link

Related:  Reason behind this self invoking anonymous function variant

Solution 6:

It’s quite simple…

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