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

232
Visualizações
How do I change textcolor with a button in javascript?

I want to change a certain part of text, named "box" in html to a different color when a button "btn" is clicked with javascript.

But I get the error "Uncaught TypeError: Cannot read properties of undefined (reading 'style')".

Here's what I did in js:

const btn = document.getElementById('btn');
const box = document.getElementById('box');

btn.addEventListener('click', function onClick(event) {
  document.box.style.color = 'black';
});

I checked different websites and for other instances, this code seems to work. Can anyone tell me where I went wrong? Thanks!

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

correct the fourth line of your code to

box.style.color = 'black';
about 4 years ago · Juan Pablo Isaza Relatório

0

const btn = document.getElementById('btn');
const box = document.getElementById('box');

btn.addEventListener('click', function onClick(event) {
  box.style.color = 'blue';
});
<button id = "btn">Click Me</button>
<p><span id = "box">Some text.</span> Some more text.</p>

You don't need to put document. You only put the element/variable.style.property = "value" Document is a element of the file: <html> and you also can only put 1 element before the style.

about 4 years ago · Juan Pablo Isaza Relatório

0

You've got a small mistake. I have adjusted it.

  1. You already fetch the box in a variable (box)
  2. you can pass to the eventListener an anonymous function

const btn = document.getElementById('btn');
const box = document.getElementById('box');

btn.addEventListener('click', (event) => {
   box.style.color = 'red';
});
<div id="box">123</div>
<button id="btn">Change</button>

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