Home > database >  Error whilst changing the colour of buttons "TypeError: null is not an object (evaluating '
Error whilst changing the colour of buttons "TypeError: null is not an object (evaluating '

Time:04-03

I am trying to change the colour of multiple buttons in my html website, however I am running into errors when it is run.

HTML:

<body style="background-color:rgb(216, 216, 216);">
             
            <button id=button0 type="button"  onclick="likeAction();">LIKE</button>
            
            <button id=button1 type="button"  onclick="likeAction();">LIKE</button>
            
            <button id=button2 type="button"  onclick="likeAction();">LIKE</button>
             
            <button id=button3 type="button"  onclick="likeAction();">LIKE</button>
            
            <button id=button4 type="button"  onclick="likeAction();">LIKE</button>
            
            <button id=button5 type="button"  onclick="likeAction();">LIKE</button>
</body>

JS:

async function likeAction(){
                for (let x = 0; x < 6; x  ) {
                    document.getElementById('button' x '').style.backgroundColor = 'salmon';
                }
            }

ERROR:

Unhandled Promise Rejection: TypeError: null is not an object (evaluating 'document.getElementById('button' x '').style')

CodePudding user response:

Change

id=button0

->

id="button0"

and change

document.getElementById('button' x '') 

->

document.getElementById('button' x)

CodePudding user response:

You need to change some code, as shown below.


First, you need to change your id attribute in your HTML to be like this, so that it isn't invalid.

<button id="<id>"></button>

Basically, surround the ID text with quotes.


Also, in your JavaScript, change your getElementById function to this.

document.getElementById("button"   x);

This is because the extra empty string is redundant.


In summary, you were getting the error as the HTML didn't understand the ID, as you hadn't typed it in properly.

  • Related