3

I have seen two ways to check if an element with a specific ID exists on the page and I was wondering why the second way works.

One way I have seen is the following and I think I understand it:

if ( $('#elementID').length > 0 ) {
  //Do something
}
else {
  //Do something else
}

Another way I have seen this done that I do not quite understand is the following:

if ( $('#elementID')[0] ) {
  //Do something
}
else {
  //Do something else
}

What does the [0] mean? I normally see [...] used for array's so is this returning an array?

Thank you.

Mdd
  • 4,140
  • 12
  • 45
  • 70
  • @jrummell Thanks, editted that. – Mdd Mar 05 '13 at 15:53
  • 1
    [0] after a variable that references an array or object will return the value at that index in the array or object. In this case, it either returns a DOM Node or undefined. A DOM Node is an object and therefore equals `true`, while `undefined` always equals `false` – Kevin B Mar 05 '13 at 15:53

4 Answers4

4

jQuery selectors return an array of values that match the selector.

The first example checks the length of that array. The second example attempts to check if the first element exists.

if ( $('elementID').length > 0 ) {
  //checks the length of the array.  If the selector hit at least 1 element it does something

if ( $('elementID')[0] ) {
  //Tries to check if the first element exists.  
  //This really should work in this case, because jQuery will return jquery objects 
  //but in the general case for checking arrays is dangerous because will be incorrect for falsy values

So in the end, both are shorthand for "If there are elements selected"

I initially said the second one was dangerous. Thats actually not true in the jQuery case, because jQuery/DOM objects will always be truthy. In general though its dangerous to check if an element exists by using if(element) because this will return false for values like 0 or "". So if you're unsure, I would recommend the first convention since it is safer in a wider variety of cases. But for this particular case, either option works.

Ben McCormick
  • 25,260
  • 12
  • 52
  • 71
  • 1
    It's flawed for regular arrays (that may contain a falsy value in the first position), but in this case it does work. – bfavaretto Mar 05 '13 at 15:53
  • Thanks! Can I ask why the second example is flawed? I editted it to add the #. Is the .length > 0 a better way to test than [0]? I just recently saw [0] and was curious about that approach. – Mdd Mar 05 '13 at 15:55
  • I actually was a bit overly harsh. This will always work in this case (I updated to show that), but for a normal array a value like 0 will return false even if its defined. – Ben McCormick Mar 05 '13 at 15:57
  • No problem. Thanks for the detailed explanation. I saw this stackoverflow thread and the accept answer suggests the $('#elementID')[0] approach which was why I was curious. I had not seen that before. http://stackoverflow.com/questions/5783280/check-if-div-with-certain-class-name-exists – Mdd Mar 05 '13 at 16:11
2

A jQuery wrapped object has all of it's elements/etc stored inside in an Array-like fashion, hence why .length works on it, and you are able to see if the selector returned any results.

$('#elementID').length

Since jQuery stores these in an Array-like fashion, you can access them individually by using the typical [] bracket notation. Note, this will also return a raw javascript HTMLElement. It removes the jQuery wrapped from it.

$('#elementID')[0] // returns the 1st element

Since in this instance, both return a truthy result, it will continue into the if statement.


// On a side note: make sure to _not_ do simply:
if ( $('#elementID') ) { }

jQuery will return an empty jQuery wrapped object (which will be -truthy-), continuing on into the if statement.

Mark Pieszak - Trilon.io
  • 61,391
  • 14
  • 82
  • 96
1

To point you into the right direction:

var test = document.getElementById('test') //returns a HTML DOM Object
var test = $('#test') //returns a jQuery Object
var test = $('#test')[0] //returns a HTML DOM Object
Ron van der Heijden
  • 14,803
  • 7
  • 58
  • 82
1

Neither of them have actually nothing directly to do with jQuery. $(selector) returns an array of jQuery objects matching the selector. Thus you can use Array.length property to check how many matches there are. Likewise you can access any items in the array through it's zero-based index. While $(selector)[0] would return the first HtmlElement object in the array, $(selector)[1] would return the second. And so forth.

While if ($(selector)[0]) may work in some cases, it doesn't return a boolean value, thus the condition is flawed and should not be used. Instead, use $(selector).length > 0.

Jani Hyytiäinen
  • 5,293
  • 36
  • 45
  • Thank you! I have been reading up on arrays as I try to learn JS and on another Stackoverflow thread recommended the $('#elementID')[0] ) approach (The top answer seen here: http://stackoverflow.com/questions/5783280/check-if-div-with-certain-class-name-exists ). Thank you for your explanation. – Mdd Mar 05 '13 at 16:08