Melissa Doll Melissa Doll - 1 month ago 5
Javascript Question

Cell data from table column Javascript

I have a table, I want to retrieve the cells innerHTML from column 2.





<tr>

<td>A</td>
<td>B</td>
<td>C</td>

</tr>

<tr>

<td>A</td>
<td>B</td>
<td>C</td>

</tr>

<tr>

<td>A</td>
<td>B</td>
<td>C</td>

</tr>




In this example I would like to return the 3 'B' cells in column 2.
Thanks in Advance Guys!

Answer

Markup:

<table id="myTable">
<tbody>
<tr>

    <td>A</td>
    <td>B</td>
    <td>C</td>

</tr>

<tr>

    <td>A</td>
    <td>B</td>
    <td>C</td>

</tr>

<tr>

    <td>A</td>
    <td>B</td>
    <td>C</td>

</tr>
</tbody>
</table>

Javascript:

var cellData = [];
var i;

var myTable = document.querySelector('#myTable');

for (i=0; i<myTable.rows.length; i++) {
  cellData.push(myTable.rows[i].cells[1].innerHTML);
}

console.log(cellData);
Comments