jQuery: Check if div with certain class name exists
Asked Answered
H

20

282

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?

Hughie answered 25/4, 2011 at 21:6 Comment(0)
G
516

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.

Goodale answered 25/4, 2011 at 21:13 Comment(7)
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...Warnerwarning
I've ended up using this solution though there are other solutions that work too. Thank you for the quick answers.Hughie
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, and here's one where it doesn't exist.Warnerwarning
And if I wan't to execute a code if a class does not exist?Billow
@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?Billow
@ThomasSebastian Try if (!$(".mydivclass")[0]){ /* do stuff */ }Goodale
as the jsperf link is not working anymore, I created a small example on JSFiddle: jsfiddle.net/cv5hd210/3Larissa
L
142

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.

Lonnielonny answered 25/4, 2011 at 21:9 Comment(2)
According to the link you provided to the tool on jsperf.com, .length currently offers the best average performance.Panada
Servers my needs with the smallest performance impact for a check.Drape
F
96

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
}
Faso answered 21/1, 2015 at 4:27 Comment(0)
H
73
$('div').hasClass('mydivclass')// Returns true if the class exist.
Hollingsworth answered 25/4, 2011 at 21:20 Comment(29)
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).Warnerwarning
@t.j. hasClass is 33% faster then the other selectors on here. Check jsperf.com/hasclass00Hollingsworth
@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: 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.Warnerwarning
@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.jsperf.com/hasclass00Hollingsworth
@Hussein: Even with only 100 divs, 7% slower on Chrome, 26% on Firefox, 91% on Opera: jsperf.com/hasclass01-with-a-few-more-divsWarnerwarning
@t.j. It's 80% faster on Firefox and IE. When you look at the overall stats, it's better to use this solution.Hollingsworth
@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.Warnerwarning
@t.j, i did that based on the question, I didn't make anything up. I beleive you did with your added code.Hollingsworth
@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: 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.Warnerwarning
100 divs still 80% faster in firefox and IE. this makes it the more suitable selector to use.Hollingsworth
@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. 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).Warnerwarning
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.Hollingsworth
@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.Warnerwarning
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 jsperf.com/hasclass00Hollingsworth
@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.Warnerwarning
@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.Hollingsworth
@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.Warnerwarning
@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. 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.Hollingsworth
@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), 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)Warnerwarning
@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)Warnerwarning
@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,Warnerwarning
@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. 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.Hollingsworth
@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 and StatCounter. Also, not for nothing, but you're coming across way aggressive and over-the-top. Try to tone it down and lighten it up.Warnerwarning
@t.j. It doesn't what site you use for browser statistics, chrome, safari and opera will comes last and way below Firefox.Hollingsworth
@Hussein: True (for now; I predict Big Things for Chrome). IE, on the other hand...Warnerwarning
@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.Hollingsworth
@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?Warnerwarning
@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.Hellhound
Not sure if it's just me but this answer appears empty on mobile using the official Stack Exchange app.Goodale
I
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

Infringe answered 11/1, 2014 at 4:5 Comment(1)
classList is supported only in IE10+: caniuse.com/classlist. You must add a polyfill github.com/eligrey/classList.js or write your own methodsCandelabra
B
25

It's quite simple...

if ($('.mydivclass').length > 0) {
  //do something
}
Bleareyed answered 25/4, 2011 at 21:8 Comment(0)
H
10

To test for div elements explicitly:

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

Hellhound answered 25/4, 2011 at 21:10 Comment(2)
This may be slightly slower than .mydivclass depending on browser and jQuery version.Hellhound
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.Warnerwarning
V
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.

Vaporization answered 23/8, 2017 at 7:4 Comment(0)
R
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
}
Rhoden answered 6/7, 2015 at 5:36 Comment(0)
T
7

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

if ($('.myDivClass').length) {
Trepidation answered 8/12, 2021 at 9:15 Comment(0)
P
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......

}
Preference answered 27/7, 2018 at 7:7 Comment(0)
H
6
if ($("#myid1").hasClass("mydivclass")){// Do any thing}
Hartsock answered 10/6, 2019 at 8:22 Comment(1)
Please give some explanation to your answerForbidden
M
5

Use this to search whole page

if($('*').hasClass('mydivclass')){
// Do Stuff
}
Minardi answered 24/7, 2019 at 7:48 Comment(0)
A
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.
}
Alarcon answered 15/10, 2019 at 6:43 Comment(0)
T
4

check if the div exists with a certain class

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

}
Trimetric answered 25/4, 2011 at 21:8 Comment(0)
I
4
if($(".myClass")[0] != undefined){
  // it exists
}else{
  // does not exist
}
Impatience answered 12/4, 2017 at 20:0 Comment(3)
Seems almost identical to this existing answer.Kweilin
Yes it does... but I tried that answer and it did not work. When I added the comparison to 'undefined' it seemed to work perfectly.Impatience
This could be faster. +1 for this.Drusy
S
4

The best way in Javascript:

if (document.getElementsByClassName("search-box").length > 0) {
// do something
}
Sweitzer answered 14/3, 2018 at 11:6 Comment(0)
C
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.

Centering answered 25/4, 2011 at 21:7 Comment(5)
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 which does what the OP actually said (even though, again, they may have meant what you've done).Warnerwarning
@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.Centering
"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. :-)Warnerwarning
@T.J. Crowder: Yeah, I think we're overthinking this.Centering
@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.Centering
F
3
var x = document.getElementsByClassName("class name");
if (x[0]) {
alert('has');
} else {
alert('no has');
}
Flyer answered 23/4, 2018 at 4:49 Comment(1)
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.Tonyatonye
S
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>
Sapindaceous answered 6/6, 2023 at 12:31 Comment(1)
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.Undershoot

© 2022 - 2024 — McMap. All rights reserved.