Javascript - Read updated HTML when executing function

Asked

Viewed 42 times

0

1 - I have two javascript functions:

var linhas = document.getElementById("tabela").getElementsByTagName("tr");
var linhaSelecionada = "";

function selecionarLinha(){
    for(var i = 0; i < linhas.length; i++){
        var linha = linhas[i];
        linha.addEventListener("click", function(){
            this.classList.toggle("selecionado");
        });
    }
    teste();
}

function teste(){
    var selecionados = document.getElementById("tabela").getElementsByClassName("selecionado");
    for(var i = 0; i < selecionados.length; i++){
        var selecionado = selecionados[i];
        selecionado = selecionado.getElementsByTagName("td");
        linhaSelecionada = selecionado[0].innerHTML;
    }
    console.log(linhaSelecionada);
}

2 - What the code does and what is my doubt:

When calling the function selectLine() through a button, I set the class of the selected row in the table with class="selected" so far it is working correctly. However, when calling the second function that should read the html and check which lines are with class="selected" no line is found with this class. I would like to know how to do so that the second function can find which lines the first function set with class="selected" without I need to click a button to select and click another button to display what was selected, that is, through a single click select and display the selected line.

1 answer

0

Good night friend, try to do the following:

function teste(){
    const selecionados = document.querySelectorAll('#tabela .selecionado')
    let linhaselecionada
 
    selecionados.forEach(selecionado => {
      const td = selecionado.querySelector('td')
      linhaselecionada = td.innerHTML
    })

    console.log(linhaSelecionada);
}

In case you are still giving error, open the browser console and copy and paste here the error so that I have more details and can better guide you.

I hope I’ve helped!

Browser other questions tagged

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