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.
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>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments