J. Pedro Ribeiro

Updating CSS Custom Properties with JavaScript

December 08, 2019

I ran into an issue this week: needed to update the colour of a pseudo element (i.e. ::before) of an element.

The problem is that pseudo elements are not part of the browser DOM API and, therefore, are not available to JavaScript. They are, in fact, part of the CSS Object Model.

My solution was to update the custom property which that pseudo element was using. It’s a rather simple solution, first select the document root element:

const root = document.documentElement;

Then update the custom property with the new value:

root.style.setProperty("--inputColour", "yellow");

Here’s the working solution:

J. Pedro Ribeiro

I’m a Brazilian front-end developer living in London. This website features some of my latest projects and my thoughts on anything web related.
You can find me on Twitter, Instagram, and LinkedIn.