Determine CSS property based on a javascript condition

Asked

Viewed 153 times

1

HTML

<tr class="linha">
 <td class="tipoMov">Receita</td>
 <td>Corte de cabelo</td>
 <td>R$20,00</td>
</tr>

Javascript

window.onload = function(){
 if(document.getElementsByClassName("tipoMov").innerHTML == 'Receita'){
   document.getElementsByClassName("linha").style.backgroundColor = "#90EE90";
 }
}

What I need is to change the background-color of the "tr" tag according to what is on the "td" tag with class "typeMov".

When I put getElementById instead of getElementsByClassName works, but I have several lines, so I could not use the ID, I need to use class.

2 answers

1

The function getElementsByClassName returns multiple results while the getElementById returns only one.

To work with the getElementsByClassName you must go through the list and change item by item.

window.onload = function(){
    const elementosHTML = document.getElementsByClassName("tipoMov")
    for(elemento of elementosHTML) {
        if(elemento.innerHTML == 'Receita'){
            elemento.style.backgroundColor = "#90EE90";
        }
    }
}
  • In case the element I want to change the background is the class "line", so the background that was changed was the class "typeMov"

1


It’s basically like the friend said in the other answer, but you can make it into shape using querySelector(".tipoMov"). When going through each row of the table, querySelector will fetch the element with the class .tipoMov and take the text inside it and compare it to Receita. If equal, apply the background color:

const linha = document.getElementsByClassName("linha");
for(let i of linha){
   if(i.querySelector(".tipoMov").textContent.trim() == "Receita"){
      i.style.backgroundColor = "#90EE90";
   }
}
<table border="1">
<tr class="linha">
 <td class="tipoMov">Receita</td>
 <td>Corte de cabelo</td>
 <td>R$20,00</td>
</tr>
<tr class="linha">
 <td class="tipoMov">Outra coisa</td>
 <td>Corte de cabelo</td>
 <td>R$20,00</td>
</tr>
<tr class="linha">
 <td class="tipoMov">Receita</td>
 <td>Corte de cabelo</td>
 <td>R$20,00</td>
</tr>
</table>

Note that I used .trim() to eliminate possible spaces in the borders of the text. This is because if you indent the text inside the td, the text will return with spaces before and after it.

For example, if you do so:

<td class="tipoMov">
   Receita
</td>

The word Receita will come with spaces, because HTML considers new lines as a white space.

Browser other questions tagged

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