How to modify CSS pseudo-elements with JavaScript or jQuery?

I’m trying to figure out how to change CSS pseudo-elements like ::before and ::after using JavaScript or jQuery. My CSS has this rule:

.myClass::after {
  content: 'hello';
}

Is there a way to change ‘hello’ to something else with JavaScript? I’ve looked around but can’t find a straightforward answer. Can anyone help me understand how to do this? I’m okay with using plain JavaScript or jQuery, whichever works better for this task. Thanks in advance for any tips or code examples!

While the previous answer provides a good workaround, there’s another approach worth considering. You can dynamically create or modify a element in your document’s head. Here’s how:

function updatePseudoElement(selector, property, value) {
    let style = document.createElement('style');
    style.innerHTML = `${selector}::after { ${property}: ${value}; }`;
    document.head.appendChild(style);
}

updatePseudoElement('.myClass', 'content', '"new content"');

This method allows you to override the existing CSS rule with a new one. It’s particularly useful when you need to change multiple properties of the pseudo-element or when you’re working with a large number of elements. Just be mindful of potential performance implications if overused.

I’ve actually tackled this issue before in a project. One effective method I found is using the getComputedStyle() function combined with a custom data attribute. Here’s what worked for me:

  1. Add a data attribute to your element:
  1. Modify your CSS:
    .myClass::after {
    content: attr(data-content);
    }

  2. Use JavaScript to update the data attribute:
    document.querySelector(‘.myClass’).dataset.content = ‘new content’;

This approach maintains a clean separation between your HTML, CSS, and JavaScript while still allowing dynamic updates to pseudo-elements. It’s been quite reliable in my experience, especially when dealing with multiple elements or frequent content changes.

hey there! u can’t directly change pseudo-elements with JS, but there’s a workaround. try using a custom CSS property (variable) in ur CSS rule, like this:

.myClass::after {
content: var(–afterContent, ‘hello’);
}

then update it with JS:

document.querySelector(‘.myClass’).style.setProperty(‘–afterContent’, “‘new content’”);

hope this helps!