Why is the <select>
and <div>
element's .length
different?
<select id="select"></select>
<div id="myDiv">My div!
<div></div>
</div>
var select = document.getElementById('select');
var myDiv = document.getElementById('myDiv');
console.log(select.length); // 0
console.log(myDiv.length); // undefined
And why does a select
with options has length > 0
, if it has options inside; but the same doesn't applies to a div
element?
Let's checkout the docs for Element.length
length
returns the number of items in a NodeList.
And:
Despite the location of this page in the reference, length is not a property of Element, but rather of a NodeList. NodeList objects are returned from a number of DOM methods, such as document.getElementsByTagName.
So document.getElementById
return a node, and not a NodeList
. So the length
property on a single node is undefined
.
You probably want to measure the length of the list of children instead.
console.log(select.children.length);
Lastly, according to the docs HTMLSelectElement
implements it's version of length
, which MDN defines as:
The number of elements in this select element.
Most elements of other types do not have this property. This is a property of HTMLSelectElement
only.
As it stands , getElementById()
returns element.
Not all elements have concept of length (define such property).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.