Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
revamp ::before
and ::after
through CSS Variables in JavaScript. Use setProperty
on the style
of a corresponding DOM node and refer those in your CSS via var(--your-variable)
. This works splendidly for dynamic content tweaks and style changes.
Update --after-content
via JavaScript, and the stage is yours — the ::after
content of your pseudo-element unfurls accordingly.
Using data attributes for dynamic content
Harness the power of HTML data attributes and the CSS attr
function, you can effortlessly alternate the ::after
content without meddling directly with the CSS:
On-the-fly update of data-after-content
attribute via jQuery modify the scene:
Toggling Classes with JavaScript
Use JavaScript to manage class lists for more complex scenarios. It simply adds or removes classes to DOM elements.
This is how the pseudo-element receive its instructions:
This is a classic separation of concerns — JavaScript for behavior, CSS for presentation.
Hovering with jQuery
Bring elements to life on hover using jQuery's .hover()
method! Add/remove a class to change the style dynamically.
Just a bit of CSS magic:
Getting existing styles
Knowing the current state can help make intelligent changes. Use window.getComputedStyle()
to get the ball rolling:
This can be a game-changer for situations where style changes are conditional on existing styles.
Custom properties and their wonders
CSS Custom Properties (Variables) ride to the rescue for modern browsers. It allows you to update properties dynamically with JavaScript without the restrictions of inline styles or proprietary hacks:
Now set the custom properties via JavaScript:
Was this article helpful?