:before
and :after
pseudo-elements are not considered actual DOM elements, therefore they cannot be manipulated directly using JavaScript.
However, a workaround is to create two separate classes with different content and styles, then toggle between them using JavaScript:
Check out this JsFiddle for an example
document.getElementById('demo').addEventListener('click', function(){
this.classList.remove('demo');
this.classList.add('New-demo');
});
.demo:after {
content: "myRuntimeValue";
color: orange;
}
.New-demo:after {
content: "Some New Content!";
color: red;
}
<p id="demo" class="demo">Click Me!</p>
By utilizing this technique, not only can you modify the content displayed, but also apply specific styles to these pseudo-elements.