DEV Community

Cassidy Williams
Cassidy Williams

Posted on • Originally published at blog.cassidoo.co

20 4 5 6 5

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!

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (1)

Collapse
 
devluc profile image
Devluc

Oh nice, great tip Cassidy

nextjs tutorial video

Youtube Tutorial Series 📺

So you built a Next.js app, but you need a clear view of the entire operation flow to be able to identify performance bottlenecks before you launch. But how do you get started? Get the essentials on tracing for Next.js from @nikolovlazar in this video series 👀

Watch the Youtube series