DEV Community

Cassidy Williams
Cassidy Williams

Posted on • Originally published at blog.cassidoo.co

Styling a CSS pseudo-element with JavaScript

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

document.querySelector("div::after");
Enter fullscreen mode Exit fullscreen mode

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);
}
Enter fullscreen mode Exit fullscreen mode

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%");
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (1)

Collapse
 
devluc profile image
Devluc

Oh nice, great tip Cassidy