Skip to content Skip to sidebar Skip to footer

How Do I Loop Through Children Objects In Javascript?

I have this code in a function: tableFields = tableFields.children; for (item in tableFields) { // Do stuff } According to a console.log of tableFields, I am getting an array

Solution 1:

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.


Solution 2:

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)});

Solution 3:

if tableFields is an array , you can loop through elements as following :

for (item in tableFields); {
     console.log(tableFields[item]);
}

by the way i saw a logical error in you'r code.just remove ; from end of for loop

right here :

for (item in tableFields); { .

this will cause you'r loop to do just nothing.and the following line will be executed only once :

// Do stuff

Solution 4:

The backwards compatible version (IE9+) is

var parent = document.querySelector(selector);
Array.prototype.forEach.call(parent.children, function(child, index){
  // Do stuff
});

The es6 way is

const parent = document.querySelector(selector);
Array.from(parent.children).forEach((child, index) => {
  // Do stuff
});

Solution 5:

Modern JS also uses the for..of to enable us to iterate DOM children objects, array, or other iterable objects. I think it is very clean and simple.

var children = tableFields.children;
for (c of children) { 
  console.log(c);
  // Do stuff with child c
}

Post a Comment for "How Do I Loop Through Children Objects In Javascript?"