3

Styling a CSS pseudo-element with JavaScript

 6 months ago
source link: https://dev.to/cassidoo/styling-a-css-pseudo-element-with-javascript-1dip
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
Cassidy Williams

Posted on Mar 5

• Originally published at blog.cassidoo.co

14 4 4 5 4

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!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK