Categories
JavaScript Answers

How to Add CSS Styles with JavaScript?

Spread the love

Sometimes, we want to add CSS styles dynamically into our web page with JavaScript.

In this article, we’ll look at ways to add CSS styles dynamically with JavaScript.

Using the window.document.styleSheets Object and the insertRule Method

We can get the first stylesheet for a document with the window.document.styleSheets property.

Then we can call the insertRule method on the returned stylesheet object.

For instance, if we have the following HTML code:

<strong>hello world</strong>

Then we can make the strong element text display in red by writing:

const [sheet] = window.document.styleSheets;
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);

We use the destructuring syntax to get the first stylesheet from the window.document.styleSheets iterable object.

Then we call insertRule on the stylesheet object with our CSS string as the first argument.

Then we should see that the strong element text is red.

Create a style Element

Another way to add CSS styles with JavaScript is to use the document.createElement method to create a style element.

For instance, if we have the following HTML code:

<strong>hello world</strong>

Then we can create the style element by writing:

const styleSheet = document.createElement("style")
styleSheet.type = "text/css"
styleSheet.innerText = 'strong { color: red; }'
document.head.appendChild(styleSheet)

We call document.createElement with 'style' to create a style element.

Then we set the type property on the resulting styleSheet object.

And then we set the innerText property to the CSS styles we want to apply.

Finally, we call document.head.appendChild with styleSheet to append the style element we created into the head element as its child.

Therefore, we should get the same result as before.

Conclusion

We can add CSS styles with JavaScript by creating a style element or getting the first style sheet with JavaScript and add the style rules we want to it.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

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