javascripthtmlcollectionfor-of-loop

Is the element accessed as the value of the name attribute of the form element HTMLCollection?


for (let i of document.formBox) {
  console.log(i)
};
<form name="formBox">
  <input name="inputOne">
  <input name="inputTwo">
  <button name='btn'>BUTTON</button>
</form>

The above code works fine. But, is document.formBox an HTMLCollection? Why can I use a for..of statement?

I thought document.formName returns HTMLElement. However, while accidentally writing that code, I was embarrassed.


Solution

  • It might be an element or a collection depending on how many elements have that name.

    for ... of will work on an element or a collection because it cares about the value being iterable, not about it being a collection.

    console.log(document.foo.toString());
    console.log(document.bar.toString());
    
    for (let x of document.bar) {
        console.log(x.toString());
    }
    <form name="foo"></form>
    <form name="foo"></form>
    
    <form name="bar"><input /><input /><input /></form>

    In the above, document.foo is an HTMLCollection (containing HTMLFormElement instances) because there are multiple forms with the name "foo"; you can use for...of to loop through the forms in that collection. But document.bar isn't an HTMLCollection because there's only one form with the name "bar". Instead, it's an HTMLFormElement. But HTMLFormElement instances are also iterable; iterating them loops through the elements in the form.

    I strongly recommend avoiding using document.nameOfElement as it is ambiguous. Stick to querySelector and querySelectorAll instead.