Cassidy Williams

Software Engineer in Chicago

Cassidy's face

Styling a CSS pseudo-element with JavaScript


In JavaScript, you can’t do some kind of query selector like:

document.querySelector("div::after");

But, with the power of CSS variables, you can still change the styles of those selectors with JavaScript!

In your CSS, pick a variable name and assign it to something:

div::after {
	/* 50px is the default value if --somewidth doesn't exist */
	width: var(--somewidth, 50px);
}

And in your JavaScript, you use the setProperty function to assign a value to that variable!

// this is just grabbing a div, you can change it to select any element
const element = document.getElementsByTagName("div")[0];

element.style.setProperty("--somewidth", "50%");

So there ya go! You can obviously make this more complex as needed. Here’s an example of all of this in action! It’s a template I made for tracking fundraising efforts (feel free to use the template on CodePen). Specifically note line 38 in the CSS, and line 25 in the JavaScript!

See the Pen Money goal tracker template by Cassidy (@cassidoo) on CodePen.


View posts by tag

#advice #personal #musings #events #technical #learning #work #meta