How do I loop through children objects in javascript?
The trick is that the DOM Element.children
attribute is not an array but an array-like collection which has length and can be indexed like an array, but it is not an array:
var children = tableFields.children;
for (var i = 0; i < children.length; i++) {
var tableChild = children[i];
// Do stuff
}
Incidentally, in general it is a better practice to iterate over an array using a basic for-loop instead of a for-in-loop.
In ECS6, one may use Array.from() or Spread array syntax:
const listItems = document.querySelector('ul').children;
const listArray = Array.from(listItems);
// or
const listArray = [...listItems];
listArray.forEach((item) => {console.log(item)});