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!

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read more

Top comments (1)

Collapse
 
devluc profile image
Devluc

Oh nice, great tip Cassidy

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay