Get column of HTML table

1

I searched here in SOpt, but I did not find that question ...

How to get all values from a column in HTML? I just figured out how to get value from a cell, the idea is to make a filter with it

I currently use a class in <td> , but I would like something I did not need to add a class for each line, with pure JavaScript, without JQuery or something like that

    
asked by anonymous 09.03.2018 / 14:01

1 answer

2

You can cycle through all the cells of the column with the document.body.querySelectorAll("table th:nth-child(2), table td:nth-child(2)") selector, and pick up the column texts that you indicate in nth-child() . In the example below, I'm picking up the second column ( nth-child(2) ). I also used the .trim() method to exclude empty spaces at the ends of cell 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>
    
09.03.2018 / 14:27