avatar
avatar

Reputation: 12495

jQuery: Check if div with certain class name exists

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?

Upvotes: 286

Views: 676862

Answers (20)

Gaurav Sharma
Gaurav Sharma

Reputation: 11

jQuery(function($){
  $("#btn1").click(function(){
      if($(this).hasClass("demo")){
            alert("HAS");
      } else {
        alert("NO HAS");
      }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btn1" class="demo">Show Text</button>

Upvotes: 1

Mohit Rathod
Mohit Rathod

Reputation: 1193

Best way is to check the length of the class as shown below:

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

Upvotes: 7

Shaan Ansari
Shaan Ansari

Reputation: 550

In Jquery you can use like this.

if ($(".className")[0]){

   // Do something if class exists

} else {

// Do something if class does not exist

}

With JavaScript

if (document.getElementsByClassName("className").length > 0) {

// Do something if class exists

}else{

    // Do something if class does not exist......

}

Upvotes: 6

Thilina
Thilina

Reputation: 93

if ($("#myid1").hasClass("mydivclass")){// Do any thing}

Upvotes: 6

Rifat Wahid Alif
Rifat Wahid Alif

Reputation: 341

Here is very sample solution for check class (hasClass) in Javascript:

const mydivclass = document.querySelector('.mydivclass');
// if 'hasClass' is exist on 'mydivclass'
if(mydivclass.classList.contains('hasClass')) {
   // do something if 'hasClass' is exist.
}

Upvotes: 5

Arosha De Silva
Arosha De Silva

Reputation: 597

Use this to search whole page

if($('*').hasClass('mydivclass')){
// Do Stuff
}

Upvotes: 5

Sheo Dayal Singh
Sheo Dayal Singh

Reputation: 1673

Here are some ways:

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

We can use any one of the abobe defined ways based on the requirement.

Upvotes: 8

Tuan Truong Quang
Tuan Truong Quang

Reputation: 91

var x = document.getElementsByClassName("class name");
if (x[0]) {
alert('has');
} else {
alert('no has');
}

Upvotes: 3

JMJ
JMJ

Reputation: 2152

The best way in Javascript:

if (document.getElementsByClassName("search-box").length > 0) {
// do something
}

Upvotes: 4

stairie
stairie

Reputation: 85

if($(".myClass")[0] != undefined){
  // it exists
}else{
  // does not exist
}

Upvotes: 4

Jitendra Damor
Jitendra Damor

Reputation: 784

The simple code is given below :

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
}

Upvotes: 7

Josh Crozier
Josh Crozier

Reputation: 240888

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
}

Upvotes: 97

Shaz
Shaz

Reputation: 15867

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.

Upvotes: 522

Ronald Coarite
Ronald Coarite

Reputation: 4726

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

Upvotes: 46

Eli
Eli

Reputation: 17825

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

$('div.mydivclass').length

So:

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

http://api.jquery.com/size/

http://api.jquery.com/length/

UPDATE

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:

http://jsperf.com/check-if-div-exists/3

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.

Upvotes: 144

Hussein
Hussein

Reputation: 42808

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

Upvotes: 74

Stefan Kendall
Stefan Kendall

Reputation: 67802

To test for div elements explicitly:

if( $('div.mydivclass').length ){...}

Upvotes: 10

neeebzz
neeebzz

Reputation: 11538

check if the div exists with a certain class

if ($(".mydivclass").length > 0) //it exists 
{

}

Upvotes: 4

methodofaction
methodofaction

Reputation: 72385

It's quite simple...

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

Upvotes: 26

Herman Schaaf
Herman Schaaf

Reputation: 48435

if ($(".mydivclass").size()){
   // code here
}

The size() method just returns the number of elements that the jQuery selector selects - in this case the number of elements with the class mydivclass. If it returns 0, the expression is false, and therefore there are none, and if it returns any other number, the divs must exist.

Upvotes: 3

Related Questions