How to create a style tag with JavaScript?

Spread the love

Sometimes, we want to create a style tag with JavaScript.

In this article, we’ll look at how to create a style tag with JavaScript.

How to create a style tag with JavaScript?

To create a style tag with JavaScript, we can use createElement.

For instance, we write

const css = "h1 { background: red; }";
const head = document.head;
const style = document.createElement("style");

head.appendChild(style);

style.type = "text/css";
style.appendChild(document.createTextNode(css));

to create the style element with createElement.

Then we append to the head element as its lastt child with

head.appendChild(style);

Then we set the style elements attributes with

style.type = "text/css";
style.appendChild(document.createTextNode(css));

We set the style.type property to set the type attribute.

And we use style.appendChild(document.createTextNode(css)); to append the text node with the css text as the last child of the style element.

Conclusion

To create a style tag with JavaScript, we can use createElement.

Leave a Reply

Your email address will not be published. Required fields are marked *