Categories
CSS

How to select and manipulate CSS pseudo-elements such as ::before and ::after using JavaScript?

Spread the love

Sometimes, we want to select and manipulate CSS pseudo-elements such as ::before and ::after using JavaScript.

In this article, we’ll look at how to select and manipulate CSS pseudo-elements such as ::before and ::after using JavaScript.

How to select and manipulate CSS pseudo-elements such as ::before and ::after using JavaScript?

To select and manipulate CSS pseudo-elements such as ::before and ::after using JavaScript, we can add a stylesheet dynamically.

For instance, we write

const str = "bar";
document.styleSheets[0].addRule("p.special:before", 'content: "' + str + '";');

to add a style rule for the part of the p element with class special.

We set the content property to the str string.

Conclusion

To select and manipulate CSS pseudo-elements such as ::before and ::after using JavaScript, we can add a stylesheet dynamically.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *