How to create a style tag using JavaScript

avatar

Borislav Hadzhiev

Fri Jan 07 20221 min read

banner

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.

index.html
<!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.

index.js
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

Use the search field on my Home Page to filter through my more than 1,000 articles.