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:

let cssText = `
@import url(';900&display=swap');

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


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: