How to Iterate Table Rows in JavaScript

HTML tables are defined with the <table> tag, containing rows <tr> and cells <td> tags. To iterate over rows in JavaScript, you can use document.querySelectorAll and forEach loops.

主页 > 博客 > How to Iterate Table Rows in JavaScript

HTML tables are defined with the <table> tag, containing rows <tr> and cells <td> tags. To iterate over rows in JavaScript, you can use document.querySelectorAll and forEach loops.

How to Iterate Table Rows in JavaScript

Iterate Table Rows Use Cases

Common use cases for iterating over table rows:

  • Collecting table data, converting to JavaScript objects or arrays
  • Applying style changes to rows like adding background colors
  • Showing/hiding rows based on cell contents

Function Overview

To iterate table rows, first get the table element, use querySelectorAll to get the <tr> row elements, then you can loop through the rows with forEach.

Syntax and Usage

Get table element:

var table = document.getElementById("myTable"); 
// or
var table = document.querySelector("table");

Get row elements:

var rows = table.querySelectorAll("tr"); 

Iterate rows:

rows.forEach(function(row) {
  // do something with row
}); 

Can also use a for loop:

for (var i = 0; i < rows.length; i++) {
  var row = rows[i];
  // do something with row   
}

Iterate Table Rows Examples

<table id="scoreTable">
  <tr><td>John</td><td>80</td></tr>
  <tr><td>Jane</td><td>90</td></tr>  
</table>  

<script>
  var table = document.getElementById("scoreTable");
  var rows = table.querySelectorAll("tr");
   
  rows.forEach(function(row) {
    row.style.backgroundColor = "grey";
  });   
</script>

The above iterates all rows and sets background color to grey.

Interactive Exercise

Output content of each row in table below:

<table id="dataTable">
  <tr><td>Name 1</td><td>Data 1</td></tr>
  <tr><td>Name 2</td><td>Data 2</td></tr>   
</table>

<script>
// your code here  
</script>

Reference Answer:

var table = document.getElementById("dataTable");  
var rows = table.querySelectorAll("tr");
 
rows.forEach(function(row) {
  var cols = row.querySelectorAll("td");     
  console.log(cols[0].textContent, cols[1].textContent);   
});

Tips

  • Get cell data with querySelectorAll on <td> elements
  • Use textContent for text contents
  • Can use for loop instead of forEach

Conclusion

After getting row elements, you can use querySelectorAll and forEach to iterate over each <tr> and access table data in JavaScript.

References

Learn more:

How to Iterate Table Rows in JavaScript
HTML tables are defined with the <table> tag, containing rows <tr> and cells <td> tags. To iterate over rows in JavaScript, you can use document.querySelectorAll and forEach loops.
JsNoteClub:Share interesting and useful JavaScript tools and tips.

除非注明,否则均为 jsnoteclub.com 原创文章,请勿转载谢谢!

本文标题:How to Iterate Table Rows in JavaScript

本文链接:https://jsnoteclub.com/blog/how-to-iterate-table-rows-in-javascript/