Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops Working with 'for' Loops The Refactor Challenge – One Solution

karan Badhwar
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
karan Badhwar
Web Development Techdegree Graduate 18,135 Points

Style Tag

Isn't it bad for the specificity if we add style tag directly as we have done here

html += <div style="background-color: ${randomRGB}">${i}</div>;

There are other ways as well right to apply CSS to the element through JavaScript?

1 Answer

Steven Parker
Steven Parker
229,657 Points

It makes sense for each DIV created here to have an inline (high specificity) style, since each one is being assigned a different color.

If you wanted to give all DIVs the same color, you could add a STYLE tag to the document instead, for example:

// do this just once, not for each new div
let style = document.createElement("style");
style.textContent = `div { background-color: ${randomRGB}; }`;
document.head.append(style);