Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

225
Vistas
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 Respuestas
Responde la pregunta

0

correct the fourth line of your code to

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

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda