Insert CSS styles with JavaScript

All the various ways to add styles using JS

By: Ajdin Imsirovic 17 January 2021

Appending a style tag to the head tag of an HTML document requires some simple DOM manipulation. In this tutorial, we’ll discuss how to do this.

We’ll discuss several ways to add various styles to a DOM tree of a web page.

1. Add Roboto font to a web page dynamically using JavaScript

Our use case scenario is: We would like to add Roboto font to a web page, dynamically, from Google fonts.

Here’s an implemenation that adds Roboto with font weights of 300 and 900:

1
2
3
4
5
6
7
8
9
let cssText = `
@import url('https://fonts.googleapis.com/css2?family=Roboto:wght@300;900&display=swap');
`;

let myStyleTag = document.createElement('style');
myStyleTag.type = 'text/css';

myStyleTag.appendChild(document.createTextNode(cssText));
document.getElementsByTagName('head')[0].appendChild('myStyleTag');

This takes care of adding a font family from Google fonts dynamically to a web page using JavaScript.

2. Append new style using setAttribute()

The setAttribute() method is great when you want to set some CSS classes or styles on an HTML element. But how do you update the CSS on an HTML element without reseting everything using setAttribute()? The trick to appending additional styles using setAttribute() is to use the getAttribute() method as the second parameter of the setAttribute() method, plus some string concatenation:

el.setAttribute('style', el.getAttribute('style')+'; color: red');

Feel free to check out my work here: