Explain Codes LogoExplain Codes Logo

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

javascript
prompt-engineering
functions
callbacks
Alex KataevbyAlex Kataev·Jan 6, 2025
TLDR

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.

// ready for some magic? document.documentElement.style.setProperty('--after-content', 'Abracadabra!');
.myElement::after { // voila! content: var(--after-content); }

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:

<div class="content-container" data-after-content="Some Insight"></div>
.content-container::after { content: attr(data-after-content); }

On-the-fly update of data-after-content attribute via jQuery modify the scene:

$('.content-container').attr('data-after-content', 'Updated Insight');

Toggling Classes with JavaScript

Use JavaScript to manage class lists for more complex scenarios. It simply adds or removes classes to DOM elements.

// Secret handshake! const element = document.querySelector('.dynamic-style'); element.classList.add('new-style');

This is how the pseudo-element receive its instructions:

.dynamic-style.new-style::after { // Say after me, content: 'Modified content'; }

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.

$('.hover-element').hover( function() { // spotlight, please! $(this).addClass('hover-active'); }, function() { // curtains down. $(this).removeClass('hover-active'); } );

Just a bit of CSS magic:

.hover-element.hover-active::before { content: 'Responsive!'; }

Getting existing styles

Knowing the current state can help make intelligent changes. Use window.getComputedStyle() to get the ball rolling:

const pseudoElementStyles = window.getComputedStyle(document.querySelector('.element'), '::after'); console.log(pseudoElementStyles.content);

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:

.element::before { content: var(--info-content, 'Fallback text'); }

Now set the custom properties via JavaScript:

element.style.setProperty('--info-content', 'Updated content');