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

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

Linda Hamilton
Release: 2024-11-06 08:08:02
Original
518 people have browsed it

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
   }  
}
Copy after login

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
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template