333

Yes, I know this has been asked a lot. But, it confuses me, since the results on google for this search show different methods (listed below)

$(document).ready(function() {
    if ($('#DivID').length){
        alert('Found with Length');
    }

    if ($('#DivID').length > 0 ) {
        alert('Found with Length bigger then Zero');
    }

    if ($('#DivID') != null ) {
        alert('Found with Not Null');
    }
});

Which one of the 3 is the correct way to check if the div exists?

EDIT: It's a pitty to see that people do not want to learn what is the better approach from the three different methods. This question is not actually on "How to check if a div exists" but it's about which method is better, and, if someone could explain, why it it better?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
Rafael Herscovici
  • 16,558
  • 19
  • 65
  • 93
  • 17
    @miku - its not a duplicate, since this is to determine the correct way, not how to. – Rafael Herscovici Aug 01 '11 at 13:41
  • 1
    #Felix kling - all 3 works on jsfiddler http://jsfiddle.net/k6aAh/1/ – Rafael Herscovici Aug 01 '11 at 13:42
  • @Dementic, yeah sure - but it's very similar - and if that top answer would be wrong, I guess one of the 73,694 pair of eyes might have spotted an error already. – miku Aug 01 '11 at 13:43
  • @Dementic, but the top answers seem to converge - a sign that they are more similar than others (at least for me) - :D / but anyhow - let the hive mind decide ... – miku Aug 01 '11 at 13:50
  • @Dementic: No, it does not work: http://jsfiddle.net/k6aAh/2/ – Felix Kling Aug 01 '11 at 14:13
  • @Felix - you remove the div from the html, how will it work? – Rafael Herscovici Aug 01 '11 at 14:15
  • 2
    @Dementic: It should show you that the third method still tells you that the element exist although it does not. What do you conclude from this? That you cannot test for existence of an element with the third method. – Felix Kling Aug 01 '11 at 14:17
  • And regarding your edit, there is no objectively measurable *better* method. Some people prefer explicit tests (second way) while others prefer implicit type conversion. As said, it's personal preference. – Felix Kling Aug 01 '11 at 14:19
  • [***¡SEE THIS ANSWER!***](http://stackoverflow.com/questions/31044/is-there-an-exists-function-for-jquery#answer-13313296) – SpYk3HH Oct 02 '13 at 23:13

3 Answers3

194

The first is the most concise, I would go with that. The first two are the same, but the first is just that little bit shorter, so you'll save on bytes. The third is plain wrong, because that condition will always evaluate true because the object will never be null or falsy for that matter.

karim79
  • 339,989
  • 67
  • 413
  • 406
  • 1
    Unless in code above they got something like $('#DivID') = null; Lol) – ZurabWeb Nov 06 '13 at 21:14
  • 9
    "The first is the most concise, I would go with that.{...}, so you'll save on bytes", very bad mindset. Maintainable code > concise code. – Niklas Ekman Nov 16 '13 at 18:30
  • 2
    @NiklasEkman - I agree that maintainability is more important than precise code, yet I was not generalising. I guess I was not being clear enough. In the case of testing the *length* of a collection, for positive non-zero it seems to me that `.length` defeats `.length > 0`, so it's kind of a double-win. Still, thanks for pointing this out. – karim79 Nov 27 '13 at 23:44
114

If you are simply checking for the existence of an ID, there is no need to go into jQuery, you could simply:

if(document.getElementById("yourid") !== null)
{
}

getElementById returns null if it can't be found.

Reference.

If however you plan to use the jQuery object later i'd suggest:

$(document).ready(function() {
    var $myDiv = $('#DivID');

    if ( $myDiv.length){
        //you can now reuse  $myDiv here, without having to select it again.
    }


});

A selector always returns a jQuery object, so there shouldn't be a need to check against null (I'd be interested if there is an edge case where you need to check for null - but I don't think there is).

If the selector doesn't find anything then length === 0 which is "falsy" (when converted to bool its false). So if it finds something then it should be "truthy" - so you don't need to check for > 0. Just for it's "truthyness"

atiquratik
  • 1,296
  • 3
  • 27
  • 34
Alex KeySmith
  • 16,657
  • 11
  • 74
  • 152
  • If you want to hurt your head, there's an interesting question on null object in JS http://stackoverflow.com/questions/801032/null-object-in-javascript – Alex KeySmith Aug 01 '11 at 14:01
  • If you're using jQuery I don't see any reason to use `getElementById`, unless you really need the performance improvement (e.g. it's in a long loop or something, though I can't think of how this would come up, that you need to run thousands of select queries over and over). It's just much more verbose, over the course of a lot of javascript that really adds up to more space and less readability. – Jamie Treworgy Aug 01 '11 at 14:09
  • True, I agree with your point @jamietre I mainly use the jQuery version, as I'm probably using the jq object elsewhere. However if you know you always going to use an ID parameter and all your doing is checking for existance of an element, having the jQuery object isn't helping much (as it's just wrapping around getElementById). I suppose the other performance benifit (if checking existance is the only need for jq - probably pretty rare) is not even needing to download the library at all. Your right, getElementById most of the time is unecessarily verbose, but it's good to know an alternative. – Alex KeySmith Aug 01 '11 at 15:45
  • getElementById doesn't work with class names for example, while $('.classname').length does. – ZurabWeb Nov 06 '13 at 21:15
  • That's true @Piero I agree. "document.queryselectorAll()" http://caniuse.com/querySelector allows you to use classnames etc, but it won't for older browsers. jQuery abstracts that so you don't need to worry about it (and in fact uses queryselectorAll in the background if available). – Alex KeySmith Nov 08 '13 at 09:16
  • checking with jquery if the div equals null didn't work for me. i prefer your method. thanks – ufk Nov 21 '13 at 11:54
  • The var $myDiv-option works on empty div's as well. So, a solution for me. – KJS Jan 06 '19 at 20:09
9

As karim79 mentioned, the first is the most concise. However I could argue that the second is more understandable as it is not obvious/known to some Javascript/jQuery programmers that non-zero/false values are evaluated to true in if-statements. And because of that, the third method is incorrect.

tskuzzy
  • 35,812
  • 14
  • 73
  • 140
  • 1
    I would argue that most JavaScript developers would know that a non-zero, positive integer is considered "truthy", but that's just my point of view :) – karim79 Aug 01 '11 at 13:52
  • 2
    I would argue that ALL Javascript developers **should** know that. But nowadays so many people develop almost exclusively in "jQuery" and lack basic Javascript fundamentals. But that's a whole different discussion :P – tskuzzy Aug 01 '11 at 13:55
  • 1
    Disagree. Testing for truthiness is pretty fundamental javascript. While it may look funny if you're more familiar with another language that doesn't have this concept, it's extremely common and once you're used to it improves readability. – Jamie Treworgy Aug 01 '11 at 13:58