cssText – Adding multiple styles to an element with vanilla JavaScript can feel a bit clunky. The most common approach I’ve seen to style elements with plain JavaScript is to grab your target element, and then add one style at a time.
Example:
// Select the element that you want to add style to it (via class here)
const el= document.querySelector(".js-style");
// Add style properties, one at a time (it's boring)
el.style.backgroundColor = "#f00"
el.style.color = "#00f"
el.style.margin= "20px 10px"
el.style.textTransform = "uppercase"
It works, but it’s boring, there’s too much repetition, and you are not applying the DRY concept (Don’t repeat yourself).
instead, you can use the cssText property.
Example:
el.style.cssText =
"background-color: #f00; color: #00f; margin: 20px 10px; text-transform: uppercase";
This will work properly, but look at the code again, it can be more readable right?
let’s use the template literals. to get a syntax like CSS.
Example:
el.style.cssText = `
background-color: #f00;
color: #00f;
margin: 20px 10px;
text-transform: uppercase;
`;
now the code is easier and more readable.
you can find more useful articles on AMK
Views:
184
No Comments on cssText – Add Multiple Styles Using JavaScript