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

98
Vistas
How to add a style to an object property

I'm a JS learner. I managed to access an object property but I would like to style it, for example - change its color.

const houseForSale = {
    material: "brick",
    size: "4 bedrooms",
    condition: "excellent",
    characteristic: "red roof"
}

const message = document.querySelector("#demo");

let styleFragment = houseForSale.characteristic;
styleFragment.style.color = "red";

let text = "The house has a " + styleFragment + ".";
console.log(text);
<p id="demo"></p>

When I do that, I get an error message: "can't access property 'color', styleFragment.style is undefined.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Text nodes (and plain strings) are not styleable - they don't have a .style property. Either create a string of HTML markup as well as, say, a <span> with a style:

const houseForSale = {
  material: "brick",
  size: "4 bedrooms",
  condition: "excellent",
  characteristic: "red roof"
};

const text = "The house has a <span style='color: red'>" + houseForSale.characteristic + "<span>.";
document.querySelector("#demo").innerHTML = text;
<p id="demo"></p>

Or explicitly create an element first, then assign to its style property.

const houseForSale = {
  material: "brick",
  size: "4 bedrooms",
  condition: "excellent",
  characteristic: "red roof"
};

const p = document.querySelector("#demo");

p.appendChild(document.createTextNode('The house has a '));

const span = p.appendChild(document.createElement('span'));
span.textContent = houseForSale.characteristic;
span.style.color = 'red';

p.appendChild(document.createTextNode('.'));
<p id="demo"></p>

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