Radek
Radek

Reputation: 3

Unable to getElementById for loop-created cell in table

I can't color my td element by javascript code. Console says

Uncaught TypeError: Cannot read property 'style' of undefined
    at index.html:96

I already tested it on basic panel:

<div id = "panel"></div>

let panel = document.getElementById('panel');
this.panel.style.backgroundColor = `rgba(${color[0]},${color[1]},${color[2]},${color[3]})`;

And it worked fine... Panel has changed color as i want.

Here is the code that won't work:

for (var i = 1; i <= 8; i++) {
    document.write("<tr>");
    for (var k = 1; k <= 8; k++) {
    document.write("<td id = ",i,k,">" + "#" + "</td>");
    }
document.write("</tr>");
}   


let cell = document.getElementById('41');


this.cell.style.color = `rgba(${color[0]},${color[1]},${color[2]},${color[3]})`;

In browser developer tools the cell already have id 41..

Some code is missing, but the necessary is here. (Element getting colored by colorpicker.) Is there a problem with generated id by for loop? How can I fix it?

Thank you for answers.

Upvotes: 0

Views: 50

Answers (1)

Quentin
Quentin

Reputation: 943589

Your first problem is that you have defined a variable called cell but are trying to access a property called cell on whatever this is.

Get rid of the this.

(If you were in the global scope and you had used var instead of let, then you would be creating a window.cell as a side effect so this.cell would work there … but you are using let so that isn't the case).


Your second problem is that the output of document.write will be buffered so that it can be inserted into the DOM after the </script> for the current script element. This won't happen until the script has finished executing.

You are using getElementById too soon. The HTML is sitting in the buffer, it hasn't been converted to DOM yet.


This is just one more reason to avoid using document.write. Use DOM methods such as createElement and appendChild instead.

As a bonus, this will give you a reference to the element so you don't need to go hunting through the DOM for it with getElementById.

Upvotes: 3

Related Questions