How to take all the <td> textContent of a table and assign it to an array?

Asked

Viewed 116 times

2

I’m wanting to get all the textContent das td that then inside a tr of a table. However, this should happen when I click on your respective parent TR.

  • These tr are generated in PHP and returned by AJAX and later inserted into tbody of the HTML table.

Goes below a part of the TR build PHP code. (Only a part of foreach. has more tds. I only put one for example):

<?php

$tabela="";

foreach($lista_ativo as $value)
{

$tabela .= "<tr class='tr-row border'>";
$tabela .= "<td class='pl-3 p-3 td-descr'>$value[descricao]</td>";

$tabela .= "<td class='text-center td-mensal border'>" . number_format($value['m1'], 0, ',', '.') . "</td>";
$tabela .= "<td class='text-center td-mensal border'>" . $value['percent_m1'] . "%</td>";


?>

How the table looks after mounted in HTML:

inserir a descrição da imagem aqui

  • Now I’d like every time I click on a TR of this, I’d take each textContent of all your TD and assign it to an array.

Below is a part of how my Javascript is getting, but I’m still not succeeding.

liberarClickTr();

function liberarClickTr() {
  //Esse Array
  let valores_td = [];

  document.querySelectorAll(".tr-row").forEach(e => {
    e.addEventListener("click", function(e) {
      tr = e.target.closest("tr");
      console.log(tr);

    });
  });
}

  • Below is what comes out of that console.log (I think it’s a good sign).

inserir a descrição da imagem aqui

  • When I click on the TR already exits the TR element on the console.log. I believe I’m almost on track.

From now on, thank you!

  • Double-clicking the same line will add duplicate text to the array.

  • Yes, but I’ll reset the array before that.

  • My intention is to get these textContent with the click on tr. I’m used to doing this with jQuery, but I would like to do this with Pure JS. I’m not a fan of that addeventlistener

2 answers

4


You can use another foreach to pick up each element and manipulate it the way you want.

liberarClickTr();

function liberarClickTr() {

document.querySelectorAll(".tr-row").forEach(e => {
    e.addEventListener("click", function(e) {
      tr = e.target.closest("tr");
        let valores_td = [];
        this.querySelectorAll("td").forEach(e =>{   
            valores_td.push(e.textContent); 
        });

        console.log(valores_td);
      })

    });
};
  • It worked too, my brothão. Just missed to play in the Array, but this we do here.

3

If you want only the column texts of the clicked row to be included in the array, you must declare the empty array within the event click.

Since the tr are the elements that trigger the event click, don’t need to use e.target.closest("tr"), just one this, which I already refer to tr, even clicking inside a td.

Then you just make one .push() with the textContent searching for all the td of the line clicked. For this you use .querySelectorAll("td") and makes a for to scroll through all columns. Also use a .trim() to remove spaces on the edges of texts:

liberarClickTr();
function liberarClickTr() {
   document.querySelectorAll(".tr-row").forEach(e => {
      e.addEventListener("click", function() {
         let valores_td = [];
         this.querySelectorAll("td").forEach(i => {
            valores_td.push(i.textContent.trim());
         });
         console.log(valores_td);
      });
   });
}
<table border="1">
   <tr class="tr-row">
      <td>
         linha1 texto1
      </td>
      <td>
         linha1 texto2
      </td>
   </tr>
   <tr class="tr-row">
      <td>
         linha2 texto1
      </td>
      <td>
         linha2 texto2
      </td>
   </tr>
</table>

  • Speak up, Samzão. Explain this For ai.

  • I created a list of us with all the td of the line: let tds = this.querySelectorAll("td");... then I go through that list with the for...of... the let i represents each element of the list. I could do a foreach: tds.forEach(i => {

  • The @Andrews answer would also solve my problem, wouldn’t it? But you answered first. HAHAHA

  • You have to test to see if it works for you.

  • I tested them both, his is just without Array.

  • And his answer isn’t about .trim() and other details, such as the issue of this. :p

Show 1 more comment

Browser other questions tagged

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