Kenshin Heng Kenshin Heng - 3 months ago 28
Javascript Question

I keep getting this error: Uncaught TypeError: Cannot read property 'style' of undefined

The error is above and it tells me that it is on line 346.
I went there and triple checked everything but nothing seems to be wrong.
The variable "cw" is changing all the time unless the below statement is true. This is because I am making a block placing thing like 2D Minecraft and "cw" is checking for water in any of all the buttons/blocks by changing from 0 to 159 and back to 0 again.
Here's the code:

if (document.getElementsByTagName("button")[cw].style.backgroundColor === "#00ced1") {

I'm not working on this anymore, but thanks Quentin for pointing out my question's flaw... I completely forgot about including the background code for some reason, and that reason is long forgotten. The code is on my old computer, but if you for some reason want it, just comment.


If you say that the cw variable is changing all the time so there could be a situation in which the document.getElementsByTagName("button")[cw] will return undefined. If this is your code and you can modified it then you can change the if statement to the following one:

if (document.getElementsByTagName("button")[cw] && document.getElementsByTagName("button")[cw].style && document.getElementsByTagName("button")[cw].style.backgroundColor === "#00ced1") {

In this situation you will receive three times the same element so you probably should add additional variable:

var element = document.getElementsByTagName("button")[cw]
if (element && && === "#00ced1") {
    // code