Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

93
Visualizações
Error whilst changing the colour of buttons "TypeError: null is not an object (evaluating 'document.getElementById('button'+x+'').style')"

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" class="block" onclick="likeAction();">LIKE</button>
            
            <button id=button1 type="button" class="block" onclick="likeAction();">LIKE</button>
            
            <button id=button2 type="button" class="block" onclick="likeAction();">LIKE</button>
             
            <button id=button3 type="button" class="block" onclick="likeAction();">LIKE</button>
            
            <button id=button4 type="button" class="block" onclick="likeAction();">LIKE</button>
            
            <button id=button5 type="button" class="block" 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')
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Change

id=button0

->

id="button0"

and change

document.getElementById('button'+x+'') 

->

document.getElementById('button'+x)
about 4 years ago · Juan Pablo Isaza Relatório

0

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.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda