<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
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.In the above,
document.foo
is anHTMLCollection
(containingHTMLFormElement
instances) because there are multiple forms with the name"foo"
; you can usefor...of
to loop through the forms in that collection. Butdocument.bar
isn’t anHTMLCollection
because there’s only one form with the name"bar"
. Instead, it’s anHTMLFormElement
. ButHTMLFormElement
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 toquerySelector
andquerySelectorAll
instead.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).