Home > Back-end >  JS function which traverses through HTML table and returns the contents of the specified row/column?
JS function which traverses through HTML table and returns the contents of the specified row/column?

Time:11-01

Currently stuck on a project which I could use a bit of help with. I have a simple HTML table like so:

<table id="table">
<tr>
<td>column0</td>
<td>column1</td>
</tr>
<tr>
<td>column0</td>
<td>column1</td>
</tr>
<tr>
<td>column0</td>
<td>column1</td>
</tr>
</table

I'm trying to create a function with parameters for the rows and columns. When the function is called, the content of the specified row and column is printed to the console.

This is what I have at the moment:

const tableId = document.getElementById("table");

function getTableContents(rowNumber, cellNumber) {
    for (var i = 0; rowNumber = tableId.rows[i]; i  ) {
        for (var j = 0; cellNumber = tableId.rows[i].cells[j]; j  ) {
            console.log(rowNumber, cellNumber);
        }  
    } 
}

getTableContents(0, 0);

At the moment it's just printing every cell, because I have the console.log command triggering every time the loop occurs. I just can't think how else to get it to work. It's very very late here and my brain is fried so a point in the right direction would be fantastic.

CodePudding user response:

Are you just looking for tableId.rows[rowNumber].cells[cellNumber]? – David

const tableId = document.getElementById("table");

function getTableContents(rowNumber, cellNumber) {
  console.log(tableId.rows[rowNumber].cells[cellNumber].innerText)

}

getTableContents(2, 0);
<table id="table">
  <tr>
    <td>column0</td>
    <td>column1</td>
  </tr>
  <tr>
    <td>column2</td>
    <td>column3</td>
  </tr>
  <tr>
    <td>column4</td>
    <td>column5</td>
  </tr>
</table>

  • Related