skip to Main Content
<form name="formBox">
    <input name="inputOne">
    <input name="inputTwo">
    <button name='btn'>BUTTON</button>
  </form>

for (let i of document.formBox) { console.log(i) };

The above code works fine. But, isn’t document.formName 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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. In modern browsers, HTMLCollection (as well as NodeList) is iterable, meaning that you can use a for…of loop to iterate over the elements contained in these collections.

    I understand the confustion because in older versions of JavaScript, these collections were not iterable, and you had to use traditional loops like for or methods like Array.prototype.forEach.call() to iterate over them.

    Meaning:

    In your code the for…of loop iterates over the elements contained in that form (the two input elements and the button in this case).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search