279

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?

basickarl
  • 37,187
  • 64
  • 214
  • 335
avatar
  • 12,087
  • 17
  • 66
  • 82

20 Answers20

513

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.

Shaz
  • 15,637
  • 3
  • 41
  • 59
  • Good point, either way it's just a property lookup. I don't care about the four characters, but this could be *clearer* depending on context... – T.J. Crowder Apr 25 '11 at 21:18
  • I've ended up using this solution though there are other solutions that work too. Thank you for the quick answers. – avatar Apr 25 '11 at 21:47
  • 1
    Interestingly, you might think throwing a `:first` on there would help performance (don't know if performance is an important criterion for @itgorilla), but whether it does varies *wildly* by browser, presumably because it changes the native features jQuery can use to do the selection. [Here's a test case where the div exists](http://jsperf.com/find-matching-div-test01), and [here's one where it doesn't exist](http://jsperf.com/find-matching-div-test02-not-found). – T.J. Crowder Apr 26 '11 at 06:10
  • And if I wan't to execute a code if a class does not exist? – Thomas Sebastian Oct 16 '14 at 09:56
  • @Shaz, thankyou I knew about the else usage but what I wanted is to run the condition **if** the class does not exist. i.e with only an if code and without else. Is that possible? – Thomas Sebastian Oct 23 '14 at 03:36
  • 2
    @ThomasSebastian Try `if (!$(".mydivclass")[0]){ /* do stuff */ }` – Shaz Oct 23 '14 at 14:18
  • as the jsperf link is not working anymore, I created a small example on JSFiddle: https://jsfiddle.net/cv5hd210/3/ – Userx10xC Feb 22 '23 at 12:21
139

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.

Eli
  • 17,397
  • 4
  • 36
  • 49
95

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
}
Community
  • 1
  • 1
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
71
$('div').hasClass('mydivclass')// Returns true if the class exist.
Hussein
  • 42,480
  • 25
  • 113
  • 143
  • 5
    True this is an alternative, but an expensive one. Will be slower than the approach used in the earlier answers (*markedly* slower, on some browsers), and have a much larger memory impact as well (jQuery has to build up an array of **all** of the `div` elements on the page, then go back and loop through them to see whether they have that class, all to throw away the array at the end). – T.J. Crowder Apr 25 '11 at 21:24
  • 4
    @t.j. `hasClass` is 33% faster then the other selectors on here. Check http://jsperf.com/hasclass00 – Hussein Apr 25 '11 at 21:30
  • 1
    @Hussein: Only with a completely unrealistic test case (two `div` elements) that side-steps the very issue I highlighted (building the array). Try it with a bunch of divs: http://jsperf.com/hasclass00/2 It's 63% slower on my copy of Chrome, 43% slower on my copy of Firefox, 98% (!) slower on Opera. But moreover, it *makes sense* that it's slower to build up a list of divs and then search it, rather than giving the selector engine all the information it needs. – T.J. Crowder Apr 25 '11 at 21:46
  • @t.j. Your added code which is not part of this questions is slowing down the script. I manually added over 100 divs and my solution came out 80% faster. Check again.http://jsperf.com/hasclass00 – Hussein Apr 25 '11 at 21:51
  • @Hussein: Even with only 100 divs, 7% slower on Chrome, 26% on Firefox, 91% on Opera: http://jsperf.com/hasclass01-with-a-few-more-divs – T.J. Crowder Apr 25 '11 at 21:52
  • @t.j. It's 80% faster on Firefox and IE. When you look at the overall stats, it's better to use this solution. – Hussein Apr 25 '11 at 21:54
  • @Hussein: Nothing to do with the prep code, I'll bet, but with the divs: You've *again* created a test case to bypass the point that I made, by making all of the divs match the selector either way (and so, again, making the whole array get loaded). (You've also created an invalid doc with duplicate `id` values.) Just a sec. – T.J. Crowder Apr 25 '11 at 21:55
  • @t.j, i did that based on the question, I didn't make anything up. I beleive you did with your added code. – Hussein Apr 25 '11 at 21:56
  • @Hussein: Chill, I didn't accuse you of making anything up. *sigh* All I said was your test case was unrealistic. And sure enough, if most of the divs don't match (the unnecessary array thing), it's slower: http://jsperf.com/hasclass01-with-a-few-more-divs 31% slower on Chrome, 47% slower on Firefox, 27% slower on IE, 99% slower on Opera. (Mind, these are all synthetic benchmarks.) So: If only a couple of divs have the class, `hasClass` is slower. If nearly all divs have the class, `hasClass` is faster on the big browsers. I know which I think is more realistic. – T.J. Crowder Apr 25 '11 at 22:06
  • 100 divs still 80% faster in firefox and IE. this makes it the more suitable selector to use. – Hussein Apr 25 '11 at 22:08
  • @Hussein: I don't think you'd seen my last post. In the normal case, no, it's not the best way to go. In the case where you expect nearly all the divs to have the class, yes, it is. Edit: Change "nearly all" in the preceding to "most", I tried the "half do, half don't" case, and `hasClass` was better there. http://jsperf.com/hasclass02-half-match Still unrealistic (to my mind; same class on half the divs on your page = suggests problem), but interesting nevertheless. I'll also point out that *none* of these tests measures the memory impact, which can be an issue for long-running pages (apps). – T.J. Crowder Apr 25 '11 at 22:16
  • Your argument is beyond the scope of this question. Read the question again. hasClass is the best selector for the question being asked and it's already proven with jsperf. – Hussein Apr 25 '11 at 23:04
  • 1
    @Hussein: Note that I've been very even-handed, and presented balanced counter-evidence to your claims. I'm sorry if I touched a nerve, that seemed to happen last time, too. Just relax, it's not a personal affront, it's a technical discussion. A thick skin and an open mind are useful on StackOverflow. – T.J. Crowder Apr 25 '11 at 23:13
  • You always get your self in arguments then later delete your comments. It's best to try things out and stick to the question being asked before making unrelated comments. I'm not making up the stats, it's very clear at http://jsperf.com/hasclass00 – Hussein Apr 25 '11 at 23:27
  • @Hussein: I haven't deleted any comments in this thread. And I have stuck to the point and stuck to making reasoned statements backed by evidence. What exactly was unrelated? No, nevermind, I don't care. Goodbye. – T.J. Crowder Apr 25 '11 at 23:29
  • @t.j. length and hasClass are nothing alike. length returns the length while hasClass returns true or false. How it's used is what matters. For the case of detecting a class, hasClass is the proper solution and works best performance wise, specially when you have allot of divs to work with. This is exactly opposite of what you posted in your comment. – Hussein Apr 25 '11 at 23:59
  • @Hussein: Did you even bother to read what I wrote, look at the evidence I gave you? Let's be clear: Your solution works. It works *well* for the case where **most** of the divs have the class. It works *poorly* (more slowly, larger memory impact) when only a few of them do. You can talk around it all you want, you can keep claiming I don't understand (I do), you can keep saying it's always better (it isn't), but it doesn't change the facts. And that really is the last reply you're getting from me, I can tell when I'm wasting my time. – T.J. Crowder Apr 26 '11 at 00:07
  • @t.j. Most of the divs do not have the same class as you stated. You seem dazed and confused. In the example i posted, 50% of the divs do not have a class. Even if non of the divs have classes, this solution is still faster. http://jsperf.com/hasclass00/3. Don't comment on my posts if you don't intend to continue the conversation or waste time as you say. – Hussein Apr 26 '11 at 01:26
  • @Hussein: With your latest example (which I notice has a lot fewer divs than the test cases you keep ignoring, and still has all those invalid duplicate `id` values), http://jsperf.com/hasclass00/3: `hasClass` is **24% slower** on Chrome 10, **42% slower** on Firefox 3.6, **96% slower** on Opera 11 (all on Linux); on Windows 7, it's **11% slower** on Chrome 10, **48% slower** on IE9, **69% slower** on Safari, and I get varying results between a tie and `length` being ~20% slower on Firefox 3.6. On Windows XP using IE7, **35% slower**. Look at the browserscope. *(cont'd)* – T.J. Crowder Apr 26 '11 at 05:27
  • @Hussein: *(continuing)* That's with your own test case. Maybe it's faster on Firefox 4 on whatever OS you're testing it on, that seems to be the only browser you tested, but in the main, cross-browser, it isn't. But **again**, these are synthetic results, which are notoriously unreliable. Building an array of all of the divs on the page, and retroactively looking to see if they have a class, just seems like a bad idea on the face of it. Sometimes things that seem that way end up, counter-intuitively, being a good idea, but the data suggests otherwise here. *(cont'd)* – T.J. Crowder Apr 26 '11 at 05:33
  • @Hussein: *(continuing)* (Odd that the browserscope only shows `1` for "# of tests", I've done multiple with each and I expect you did with FF4.) My test cases with a sig. number of divs show that when the number of non-matching divs increases, the `hasClass` solution degrades, presumably because the avoidable array gets bigger. People use a **lot** of divs on their pages. Anyway, the test cases are there for anyone to try (@lurkers: mind the date/times on them), and separately I think I've made my theoretical point. This has all be a lot more time than either of us should have spent. Peace, – T.J. Crowder Apr 26 '11 at 05:36
  • @t.j. You need to educate yourself about browser statistics before wasting your time posting useless comments. 42% - 46% of users used Firefox between 2008 and 2011, That's half the population. http://www.w3schools.com/browsers/browsers_stats.asp. It's the most important browser. As for opera and safari, statistics are between 2%-4%. If these are the browsers you base your selector performance on, congratulations. – Hussein Apr 26 '11 at 06:44
  • @Hussein: LOL You're citing *w3schools* as an authoritative source? Pull the other one, it's got bells on. Try sources that *aren't* biased dramatically to developers (they say that themselves, look on the very page you linked), like [Net Applications](http://marketshare.hitslink.com/browser-market-share.aspx?qprid=2) and [StatCounter](http://gs.statcounter.com/#browser_version-ww-monthly-201003-201103). Also, not for nothing, but you're coming across **way** aggressive and over-the-top. Try to tone it down and lighten it up. – T.J. Crowder Apr 26 '11 at 06:57
  • @t.j. It doesn't what site you use for browser statistics, chrome, safari and opera will comes last and way below Firefox. – Hussein Apr 26 '11 at 07:02
  • @Hussein: True (for now; I predict Big Things for Chrome). IE, on the other hand... – T.J. Crowder Apr 26 '11 at 07:04
  • @t.j. We do not give answers based future browser predictions. All along you've been focusing on safari, chrome and opera and ignoring the fact that Firefox make 3 times the population of all 3 combined. IE is another browser that cannot be overlooked. The selector i provided is 80% faster in both IE and Firefox. Another thing you need to keep in mind is performance will not be noticeable to the naked eye in whatever browser you are using, unless of course you count time in nanoseconds. – Hussein Apr 26 '11 at 07:53
  • @Hussein: *"The selector i provided is 80% faster in both IE and Firefox"* No, it isn't; go back and look at the browserscope. But I agree the difference *in processing time* is unlikely to be noticeable. The memory impact on modern pages with hundreds of divs, though, I'm not so sure. Anyway. Agree to disagree on this incredibly trivial point? Can we move on now? – T.J. Crowder Apr 26 '11 at 07:58
  • 1
    @Hussein: The HTML5 css selector means that this will almost certainly always be the worst possible way to do this. -1 for not simply deleting your post. – Stefan Kendall Apr 26 '11 at 18:31
  • Not sure if it's just me but this answer appears empty on mobile using the official Stack Exchange app. – Shaz Aug 07 '14 at 19:47
46

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

Community
  • 1
  • 1
Ronald Coarite
  • 4,460
  • 27
  • 31
  • 1
    classList is supported only in IE10+: http://caniuse.com/classlist. You must add a polyfill https://github.com/eligrey/classList.js or write your own methods – Andrei Drynov Jun 17 '14 at 16:06
25

It's quite simple...

if ($('.mydivclass').length > 0) {
  //do something
}
methodofaction
  • 70,885
  • 21
  • 151
  • 164
10

To test for div elements explicitly:

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

Stefan Kendall
  • 66,414
  • 68
  • 253
  • 406
  • This may be slightly slower than `.mydivclass` depending on browser and jQuery version. – Stefan Kendall Apr 25 '11 at 21:11
  • True, but the OP did specifically say *"jQuery - check if **div** with certain class name exists*" (my emphasis), so you get my vote for being the first to actually include the `div` part of the selector. – T.J. Crowder Apr 25 '11 at 21:13
8

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.

dawsnap
  • 994
  • 9
  • 21
Sheo Dayal Singh
  • 1,591
  • 19
  • 11
7

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
}
Jitendra Damor
  • 774
  • 17
  • 27
7

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

if ($('.myDivClass').length) {
Mohit Rathod
  • 1,057
  • 1
  • 19
  • 33
6

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

}
ByteMe
  • 3
  • 2
Shaan Ansari
  • 510
  • 6
  • 10
6
if ($("#myid1").hasClass("mydivclass")){// Do any thing}
James
  • 4,644
  • 5
  • 37
  • 48
Thilina
  • 93
  • 2
  • 7
5

Use this to search whole page

if($('*').hasClass('mydivclass')){
// Do Stuff
}
Arosha De Silva
  • 597
  • 8
  • 18
5

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.
}
jeprubio
  • 17,312
  • 5
  • 45
  • 56
4
if($(".myClass")[0] != undefined){
  // it exists
}else{
  // does not exist
}
stairie
  • 85
  • 7
4

The best way in Javascript:

if (document.getElementsByClassName("search-box").length > 0) {
// do something
}
JMJ
  • 2,034
  • 2
  • 16
  • 17
4

check if the div exists with a certain class

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

}
neebz
  • 11,465
  • 7
  • 47
  • 64
3
var x = document.getElementsByClassName("class name");
if (x[0]) {
alert('has');
} else {
alert('no has');
}
  • While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Vishal Chhodwani Apr 23 '18 at 05:35
3
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.

Herman Schaaf
  • 46,821
  • 21
  • 100
  • 139
  • 2
    Why call a method when there's the `length` property? Also, this checks for *any* element with that class, not just a `div`. (Now, that may be what the OP meant, even if not what he/she said.) See [Stefan Kendall's answer](http://stackoverflow.com/questions/5783280/jquery-check-if-div-with-certain-class-name-exists/5783328#5783328) which does what the OP actually said (even though, again, they may have meant what you've done). – T.J. Crowder Apr 25 '11 at 21:14
  • 1
    @T.J. Crowder: Well, personal taste really - I just feel the size() method is there - why not use it. The extra overhead in calling a function (unless you're doing it 1000 times in a loop) is so minimal, I'd rather go for the bit of clarity in code. On your second point - yes, I changed my original answer to remove the `div` part, for two reasons: 1) the selector is not that bounded to the fact that OP uses a `div` element (it could change in the future), and 2) in most browsers and versions of jQuery, AFAIK, this should be faster. – Herman Schaaf Apr 25 '11 at 21:19
  • *"I just feel the size() method is there - why not use it"* Um, okay. The `length` property is there, why not use it? But if it's your preference, fair 'nuff. On the other, I didn't know you'd edited it out. If I were going to do that, I'd've left it in (again, he specifically said *"...if **div** with..."* (my emphasis) and then mentioned additionally that if it didn't matter whether it was a `div` or not, you could ditch that part. But whatever. :-) – T.J. Crowder Apr 25 '11 at 21:22
  • @T.J. Crowder: Yeah, I think we're overthinking this. – Herman Schaaf Apr 25 '11 at 21:24
  • @T.J. Crowder: But in my defense, though this is not the place for the discussion: I feel the `size()` method is there to make it clear that you're counting the number of elements in a jQuery selector, and not just any old array. But again, that's just my preference. – Herman Schaaf Apr 25 '11 at 21:26
1

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>
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 06 '23 at 13:20