Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does converting a select element to an array return an array of children elements?

I found something interesting when I accidentally used querySelector instead of querySelectorAll while selecting some elements from the page. I normally convert static node lists to an array directly after the query. But since querySelector just returns the first matching node it finds, and not a NodeList, my script attempted to convert the select node to an array. Instead of returning an empty array, it returned the children of the select element.

Why does converting a select element to an array return the children nodes? This does not work for other elements like div:

var selectParent = document.querySelector('.selectParent');
var selectArray = Array.from(selectParent);
console.log(selectArray);

var divParent = document.querySelector('.divParent');
var divArray = Array.from(divParent);
console.log(divArray);
<select class="selectParent">
  <option>Option 1</option>
  <option>Option 2</option>
</select>

<div class="divParent">
  <div>Div 1</div>
  <div>Div 2</div>
</div>
like image 667
KevBot Avatar asked Feb 21 '26 22:02

KevBot


1 Answers

It's mostly a historic compatibiilty thing. HTMLSelectElement has the two key things it needs to be array-like:

  • A length
  • Index-style access

...and those two things relate to its options: length is the number of option elements in the box, and [0], [1], etc. access those option elements.

The key quotes from the link above are:

The options collection is also mirrored on the HTMLSelectElement object. The supported property indices at any instant are the indices supported by the object returned by the options attribute at that instant.

and

The length IDL attribute must return the number of nodes represented by the options collection...

like image 114
T.J. Crowder Avatar answered Feb 23 '26 11:02

T.J. Crowder