In my previous article, we looked at different ways to get style information from an HTML element using JavaScript. Today, you'll learn how to apply CSS styles to HTML elements with JavaScript.

Let us say we have the following <div> element:

<div class="pizza">Hot, spicy, pizza 🍕</div>

Now, we want to change its text, background colors, and font style CSS properties using JavaScript. What should we do? There are multiple options available in JavaScript.

Inline Styles

The easiest and straightforward way to change the CSS styles of an element with JavaScript is by using the DOM style property.

All you need to do is fetch the element from DOM and change its inline styles:

const pizza = document.querySelector('.pizza')

// change the text color to white
pizza.style.color = 'white'

// set background color to blue
pizza.style.backgroundColor = 'blue'

// change font style to italic
pizza.style.fontStyle = 'italic'

The style property uses the camel-case naming conventions for CSS properties and applies styles inline to the element:

<div class="pizza" style="color: white; background-color: blue; font-style: italic;">Hot, spicy, pizza 🍕</div>

Global Styles

Another way is to create a <style> element, inject your CSS properties, and append it to the DOM. This option is beneficial if you want to apply styles to multiple HTML elements instead of just one.

First, let us create a <style> element:

const style = document.createElement('style')

Next, add the CSS styles to the above tag using innerHTML:

style.innerHTML = `
    .pizza {
        color: white;
        background-color: blue;
        font-style: italic;
    }
`

Finally, append the style element to the DOM. To do this, get the <head> tag using document.head, and then call the appendChild() method on it to append the style element:

document.head.appendChild(style)

Here is the complete JavaScript code snippet:

// create an element
const style = document.createElement('style')

// add CSS styles
style.innerHTML = `
    .pizza {
        color: white;
        background-color: blue;
        font-style: italic;
    }
`

// append to DOM
document.head.appendChild(style)

CSS Object Model (CSSOM) InsertRule()

According to MDN:

The CSS Object Model is a set of APIs allowing the manipulation of CSS from JavaScript. It is much like the DOM, but for the CSS rather than the HTML. It allows users to read and modify [the] CSS style dynamically.

The CSSStyleSheet.insertRule() method inserts a new CSS rule to a stylesheet. Here is how you can use this method to add styles to the above HTML element:

// create an new style
const style = document.createElement('style')

// append to DOM
document.head.appendChild(style)

// insert CSS Rule
style.sheet.insertRule(`
    .pizza {
        color: white;
        background-color: blue;
        font-style: italic;
    }
`)

It is not really required to create a new <style> element. You can use existing <style> elements as well as external stylesheets to add CSS rules using insertRule().

The insertRule() method works in all modern browsers, including Internet Explorer 9 and higher.

Constructable Stylesheets

Constructable Stylesheets is a modern way of creating and distributing reusable styles when working with the Shadow DOM.

Here is an example that creates a Constructable Stylesheets and appends it to the Shadow DOM:

// create a new shared stylesheet
const sheet = new CSSStyleSheet()

// add CSS styles
sheet.replaceSync(`
    .pizza {
        color: white;
        background-color: blue;
        font-style: italic;
    }
`)

// apply the stylesheet to a document
document.adoptedStyleSheets = [sheet]

Conclusion

In this article, we looked at four ways to add CSS styles to an HTML element in JavaScript.

So, which method should you use? It depends on what you want to achieve by dynamically changing the CSS.

If you only want to modify CSS styles for a single element, it is better to use the style property. This property changes the inline styles for a specific HTML element without affecting global styles.

If you want to apply a style to a set of HTML elements, create a new <style> tag with the necessary CSS properties and append it to the document.

Read Next: How to add multiple CSS styles using JavaScript

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.