How to create a style tag using JavaScript


Borislav Hadzhiev

Fri Jan 07 20221 min read


Photo by Ryan Pouncy

Create a style tag using JavaScript #

To create a style tag:

  1. Use the document.createElement() method to create the style tag.
  2. Use the textContent property to assign styles to the tag.
  3. Add the style tag to the head using the appendChild() method.

Here is the HTML for the examples in this article.

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <div id="box">Apple, Pear, Banana</div> <script src="index.js"></script> </body> </html>

And here is the related JavaScript code.

const style = document.createElement('style'); style.textContent = ` #box { width: 100px; height: 100px; background-color: salmon; color: white; } body { background-color: lightgrey; } `; document.head.appendChild(style);

We used the document.createElement to create a style element.

The only parameter we passed to the method is a string that specifies the type of element to be created.

The createElement method returns the newly created element.

We used the textContent property to assign some styles on the element.

Notice that we used backticks `` (not single quotes) to be able to use a multi-line string when setting the element's text content.

The textContent property represents the text content of the element and its descendants, which is exactly what we need when adding styles to a style tag.

The document.head property returns the head element of the current document.

We called the appendChild method to append the style tag to the head element on the page.

If I open the page from the example, I can see that the style tag has been created successfully.

style tag created

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee