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

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


You could also pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:

In HTML:

<span>foo</span>

In jQuery:

$('span').hover(function(){    $(this).attr('data-content','bar');});

In CSS:

span:after {    content: attr(data-content) ' any other text you may want';}

If you want to prevent the 'other text' from showing up, you could combine this with seucolega's solution like this:

In HTML:

<span>foo</span>

In jQuery:

$('span').hover(function(){    $(this).addClass('change').attr('data-content','bar');});

In CSS:

span.change:after {    content: attr(data-content) ' any other text you may want';}


You'd think this would be a simple question to answer, with everything else that jQuery can do. Unfortunately, the problem comes down to a technical issue: css :after and :before rules aren't part of the DOM, and therefore can't be altered using jQuery's DOM methods.

There are ways to manipulate these elements using JavaScript and/or CSS workarounds; which one you use depends on your exact requirements.


I'm going to start with what's widely considered the "best" approach:

1) Add/remove a predetermined class

In this approach, you've already created a class in your CSS with a different :after or :before style. Place this "new" class later in your stylesheet to make sure it overrides:

p:before {    content: "foo";}p.special:before {    content: "bar";}

Then you can easily add or remove this class using jQuery (or vanilla JavaScript):

$('p').on('click', function() {    $(this).toggleClass('special');});