1

I been trying to find a way to loop through each rows of a table using foreach loop. is that something possible?

I am not asking for an alternative of foreach loop, I am wondering if I can loop using foreach, I know I can do other ways, so please keep that in mind when trying to answer.

I have tried the followings:

var table_rows = document.getElementById("table_information_layout_id");
table_rows.forEach(function (val){
}

var table_rows = document.getElementById("table_information_layout_id").rows;
table_rows.forEach(function (val){
}

None of the above works, as I get the error UncaughtTypeError table_rows.foreach is not a function

  • Simply use a regular `for` – Cleptus Mar 22 '18 at 10:49
  • `.getElementById()` returns one element only, hence there's nothing to "loop". Have a look at [`.getElementsByTagName()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByTagName) or [`.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll). The first one won't have a `.forEach()`, the second one "may" have a `.forEach()` - but that can be easily determined by reading the documentation. – Andreas Mar 22 '18 at 10:49
  • Yes i know i can do with normal for, just wondering if there is a way with foreach –  Mar 22 '18 at 10:50

2 Answers2

1

document.getElementById("table_information_layout_id").rows returns a HTMLCollection that does not contains the .forEach method. If you really want to have all Array properties you can use Array.from(rows)

Array.from(document.getElementById("teste").rows).forEach((row) => {
   console.log(row);
});

For more details see this: https://stackoverflow.com/a/22754453/4120554

Marco Talento
  • 2,335
  • 2
  • 19
  • 31
0

You can iterate table using jquery .each method