Home > Enterprise >  How to add a style to an object property
How to add a style to an object property

Time:08-28

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.

CodePudding user response:

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>

CodePudding user response:

styleFragment.style is undefined because you set it as houseForSale.characteristic which is a string:

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

What you want is to probably set the style property of message:

message.style.color = "red";
  • Related