Take column from HTML table

Asked

Viewed 673 times

1

I searched here at Sopt, but I didn’t find this question...

How to get all values of a column in HTML? I just found how to get value from a cell, the idea is to then make a filter with the same

Currently I use a class in <td>, but would like something that doesn’t need to add a class to each line, with pure Javascript, without Jquery or something like that

1 answer

2


You can scroll through all cells in the column with the selector document.body.querySelectorAll("table th:nth-child(2), table td:nth-child(2)"), and go picking up the texts of the column that you indicate in nth-child(). In the example below, I’m taking the second column (nth-child(2)). I also used the method .trim() to exclude empty spaces at the ends of the cells' texts:

document.addEventListener("DOMContentLoaded", function(){
   
   var tabela = document.body.querySelectorAll("table th:nth-child(2), table td:nth-child(2)");
   
   for(var x=0; x<tabela.length; x++){
      console.log(tabela[x].textContent.trim());
   }
   
});
<table border="1">
   <th>
      th1
   </th>
   <th>
      th2
   </th>
   <tbody>
      <tr>
         <td>
            coluna 1 linha1
         </td>
         <td>
            coluna 2 linha1
         </td>
      </tr>
      <tr>
         <td>
            coluna 1 linha2
         </td>
         <td>
           coluna 2 linha2
         </td>
      </tr>
   </tbody>
</table>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.