How to change the color of a row in the HTML table in Javascript

Asked

Viewed 1,820 times

-1

By clicking the button, I want to change the row color of an HTML table if it has the same value as my text box. My table:

<table id="tablefc" border="4">
        <tr>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Age</th>
        </tr>
        <tr>
            <td>Frank</td>
            <td>Nenjim</td>
            <td>19</td>
        </tr>
        <tr>
            <td>Alex</td>
            <td>Ferreira</td>
            <td>23</td>
        </tr>
        <tr>
            <td>Bill</td>
            <td>Airman</td>
            <td>30</td>
        </tr>
        <tr>
            <td>Ali</td>
            <td>Bergen</td>
            <td>27</td>
        </tr>
       </table>      


    <input type="text" id="searchtxt">
    <button onclick="findcolor()">Find and color the row</button>


My Javascript code

function findcolor()
{
    var srch = document.getElementById("searchtxt").value; 
    var index, localizado;

    for(var i=1; i < tablefc.rows.length; i++)
        {
            if (srch === tablefc.rows[i].cells[1].innerHTML)
                {
                    console.log('found');
                    document.getElementById("searchtxt").value = localizado
                } else {
                    console.log('not found');
                }
        }

2 answers

2

One possibility is to use querySelectAll() in the document to select all rows of your table in an array, then remove the title with Array.prototype.shift() and the remaining lines for each cell by making the comparison with the text in <input>:

function findcolor() {
  //Pega o texto do <input> e joga para maiúscula objetivando a posterior comparação case-insensitive
  let srch = document.getElementById("searchtxt").value.toUpperCase();
  //Seleciona as linhas da tabela em um array
  let rows = [...document.querySelectorAll('#tablefc tr')];
  //Descarta o título da tabela
  rows.shift();
  //Para cada linha da tabela
  rows.forEach((item) => {
    item.style.backgroundColor = 'white'; // Restaura a cor de fundo 
    //Quebra a linha em células e itera sobre elas 
    [...item.querySelectorAll(`td`)].forEach((column) => {
      //Faz a comparação case-insensitive entre o texto da célula e o texto do <input>
      if (column.innerText.toUpperCase() == srch) {
        //Se a comparação por positiva...
        item.style.backgroundColor = 'yellow'; // ..marca a linha
      }
    });
  });
}
tr {
  background-color: white;
}
<table id="tablefc" border="4">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Frank</td>
    <td>Nenjim</td>
    <td>19</td>
  </tr>
  <tr>
    <td>Alex</td>
    <td>Ferreira</td>
    <td>23</td>
  </tr>
  <tr>
    <td>Bill</td>
    <td>Airman</td>
    <td>30</td>
  </tr>
  <tr>
    <td>Ali</td>
    <td>Bergen</td>
    <td>27</td>
  </tr>
</table>


<input type="text" id="searchtxt">
<button onclick="findcolor()">Find and color the row</button>

Another possibility is to do a search with Xpath using the method document.evaluate() returning a snapshot ordered from the DOM concerning its table:

//Pega a tabela para posterior consulta
let table = document.getElementById("tablefc");

function findcolor() {
  //Pega o texto do <input> objetivando a posterior comparação case-sensitive
  let sch = document.getElementById("searchtxt").value;
  // Busca por todas a linhas da tabela menos o cabeçalho e itera por elas
  findNodes(`//tr[position()>1]`).forEach((element) => {
    element.style.background = 'white'; //Restaura a cor de fundo
  });
  // Busca por todas a células da tabela, cujo o texto seja igual do <input>, menos as do cabeçalho e itera por elas
  findNodes(`//tr[position()>1]/td[text() = "${sch}"]`).forEach((element) => {
    element.parentElement.style.background = 'red' //Ajusta a cor de fundo da linha
  });
}

function findNodes(searchtxt) {
  let result = []; 
  //Avalia a expressão XPath passada em searchtxt e tira instantâneo do DOM
  let nodes = document.evaluate(searchtxt, table, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
  //Itera pelos instantâneos
  for (let i = 0; i < nodes.snapshotLength; i++) {
    result.push(nodes.snapshotItem(i)); //Adiciona cada um deles ao resultado
  }
  return result;
}
tr {
  background-color: white
}
<table id="tablefc" border="4">
  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
  </tr>
  <tr>
    <td>Frank</td>
    <td>Nenjim</td>
    <td>19</td>
  </tr>
  <tr>
    <td>Alex</td>
    <td>Ferreira</td>
    <td>23</td>
  </tr>
  <tr>
    <td>Bill</td>
    <td>Airman</td>
    <td>30</td>
  </tr>
  <tr>
    <td>Ali</td>
    <td>Bergen</td>
    <td>27</td>
  </tr>
</table>

<input type="text" id="searchtxt">
<button onclick="findcolor()">Find and color the row</button>

1

First of all, in your code you scroll through all the rows but don’t scroll through all the columns, instead you just check the index column 1.

Soon, you could never find the value 19 which is in the index column 2 or the name Frank which is in the first index for example.

What you should do then is create two loops for to search for the value in each column of each row of your table. See below for the structure:

for (let row = 1; row < tablefc.rows.length; row++){
    for (let column = 0; column < tablefc.rows[row].cells.length; column++){

        let item = table.rows[row].cells[column];

        if (item.innerText == search){
            // Código...
        }
    }
}

To change the style of an element with Javascript, you must use the attribute style with the property you want to change.

So, assign the color you want using the property style.background. Example:

elemento.style.background = "#ff0";  // Eu também poderia colocar "rgb(255, 255, 0)"

Below is the code I made that meets your need:

function findcolor(){

    var search = document.getElementById("searchtxt").value; 
    var table = document.getElementById("tablefc");

    for (let row = 1; row < tablefc.rows.length; row++){

        for (let column = 0; column < tablefc.rows[row].cells.length; column++){

            let item = table.rows[row].cells[column];
            let parent = item.parentElement;

            if (item.innerText == search){
                parent.style.background = "#f00"; // Pinta a linha encontrada de vermelho.
                break;
            }

            parent.style.background = "#fff"; // Pinta de branco se não for a linha correta.
        } 
    }
}

Browser other questions tagged

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