最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - What is the difference between .length and [0] to check if an element with an ID exists - Stack Overflow

programmeradmin0浏览0评论

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.

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.

Share Improve this question asked Mar 5, 2013 at 15:49 MddMdd 4,45012 gold badges48 silver badges71 bronze badges 2
  • @jrummell Thanks, editted that. – Mdd Commented Mar 5, 2013 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 Commented Mar 5, 2013 at 15:53
Add a ment  | 

4 Answers 4

Reset to default 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 remend the first convention since it is safer in a wider variety of cases. But for this particular case, either option works.

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.

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

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论