Home  >  Article  >  Web Front-end  >  How do I iterate through table rows and cells in Javascript?

How do I iterate through table rows and cells in Javascript?

Linda Hamilton
Linda HamiltonOriginal
2024-11-06 08:08:02432browse

How do I iterate through table rows and cells in Javascript?

Iterating Through Table Rows and Cells in JavaScript

When working with HTML tables, it's often necessary to iterate through their rows and cells to retrieve data or perform calculations. Here are two ways to achieve this using JavaScript:

Option 1: Iterating Through Rows and Columns

To iterate through each row and column in a table, use the following syntax:

var table = document.getElementById("mytab1");
for (var i = 0, row; row = table.rows[i]; i++) {
   // Iterate through rows
   for (var j = 0, col; col = row.cells[j]; j++) {
     // Iterate through columns
   }  
}

In this loop, row represents the current row, and col represents the current cell. You can access the data within a cell using col.innerHTML.

Option 2: Iterating Through Cells Only

If you only want to iterate through the cells, ignoring the rows, use the following code:

var table = document.getElementById("mytab1");
for (var i = 0, cell; cell = table.cells[i]; i++) {
     // Iterate through cells
}

In this loop, cell represents the current cell, and you can access its data using cell.innerHTML.

The above is the detailed content of How do I iterate through table rows and cells in Javascript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn