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.
It might be an element or a collection depending on how many elements have that name.
for ... ofwill 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.foois anHTMLCollection(containingHTMLFormElementinstances) because there are multiple forms with the name"foo"; you can usefor...ofto loop through the forms in that collection. Butdocument.barisn't anHTMLCollectionbecause there's only one form with the name"bar". Instead, it's anHTMLFormElement. ButHTMLFormElementinstances are also iterable; iterating them loops through the elements in the form.I strongly recommend avoiding using
document.nameOfElementas it is ambiguous. Stick toquerySelectorandquerySelectorAllinstead.