Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading