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

132
Vistas
Javascript Element.style CSSStyleDeclaration object's properties look wierd?

Let's say I have a button in a HTML file,

<button id="btn">Click Me</button>

Use JavaScript to change the color of that button to red.

const btn = document.querySelector('#btn');
btn.style['background-color'] = 'red';

Then I checked the btn.style['background-color']. It showed red.

btn.addEventListener('click', () => {
    console.log(`This button is in ${btn.style['background-color']}`)
});

So I expected that my btn.style object should look like this,

{
  ... ,
  "background-color": "red",
  ... 
}

But when I print them in the console, why the key-value pair is 0: "background-color", and where is value red?

btn.addEventListener('click', () => console.dir(btn.style));

enter image description here

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

The CSSStyleDeclaration object is a bit exotic. If you look at btn.style["background-color"] or btn.style.backgroundColor directly, you'll see red (or some representation of red, it varies by browser).

const btn = document.querySelector('#btn');
btn.style['background-color'] = 'red';

btn.addEventListener('click', () => {
    console.log(btn.style["background-color"]);
    console.log(btn.style.backgroundColor);
});
<button id="btn">Click Me</button>

In the console output you showed, you'll find it under backgroundColor:

console output showing backgroundColor: red with a circle around it

over 4 years ago · Santiago Trujillo 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