0
Guys I’m not able to change the background-color of my cells through their ids using Javascript. Gives the following error: Uncaught Typeerror: Cannot read Property 'style' of null.
Does anyone know how to solve? Follows below my code:
function criarTabela(){
// vamos criar o elemento HTML table
var tabela = document.createElement("table");
tabela.border = "1px";
tabela.cellSpacing = "0px";
tabela.cellPadding = "3px";
// vamos criar o corpo da tabela, ou seja, o tbody
var corpo = document.createElement("tbody");
tabela.appendChild(corpo);
// vamos criar três linhas contendo quatro células cada uma
for(var i = 0; i < 151; i++){
var linha = corpo.insertRow(-1);
for(var j = 0; j < 5; j++){
var celula = linha.insertCell(-1);
celula.setAttribute("id", "lin"+i+"col"+j);
}
}
// vamos anexar a tabela recém-criada a um elemento div
var container = document.getElementById("container");
container.appendChild(tabela);
}
cria.addEventListener('click', criarTabela);
let lin1col0 = document.getElementById('lin1col0');
let lin2col0 = document.getElementById('lin2col0');
let lin3col0 = document.getElementById('lin3col0');
let lin4col0 = document.getElementById('lin4col0');
let lin5col0 = document.getElementById('lin5col0');
let num = 1;
switch(num){
case 1:
lin1col0.style.backgroundColor = "red";
break;
case 2:
lin2col0.style.backgroundColor ="red";
break;
case 3:
lin3col0.style.backgroundColor = "red";
break;
case 4:
lin4col0.style.backgroundColor = "red";
break;
case 5:
lin5col0.style.backgroundColor = "red";
break;
default:
alert("Erro!");
}
}
It helps to put the rest of the code. See above.
backgroundColor
is not a method/function, but a property. To modify, you must assign a value. Ex:lin4col0.style.backgroundColor = "red"
; Still, the mistakeUncaught TypeError: Cannot read property 'style' of null.
indicates that you are not getting the element (either you are not getting the Id right, or you ran the JS before the DOM is ready), but since the question lacks a [mcve] it is difficult to give details.– Bacco