Sometimes, we want to add CSS to the HTML head element in JavaScript.
In this article, we’ll look at how to add CSS to the HTML head element in JavaScript.
How to add CSS to the HTML head element in JavaScript?
To add CSS to the HTML head element in JavaScript, we use createElement and appendChild.
For instance, we write
const addCssToDocument = (css) => {
const style = document.createElement("style");
style.innerText = css;
document.head.appendChild(style);
};
to define the addCssToDocument function.
In it, we call createElement to create a style element.
Then we set its innerText property to a css string.
Next, we call document.head.appendChild with style to append the style element has the head element’s last child.
Conclusion
To add CSS to the HTML head element in JavaScript, we use createElement and appendChild.