Is there any way to select/manipulate CSS pseudo-elements such as ::before
and ::after
(and the old version with one semi-colon) using jQuery?
For example, my stylesheet has the following rule:
.span::after{ content:'foo' }
How can I change 'foo' to 'bar' using vanilla JS or jQuery?
Special welcome offer: get $100 of free credit. CSS ::before and ::after pseudo-elements allow you to insert “content” before and after any non-replaced element (e.g. they work on a <div> but not an <input> ). This effectively allows you to show something on a web page that might not be present in the HTML content.
In general, if we want to change anything in pseudo elements through JavaScript, we do it in the following way: Create CSS classes on element, which will change pseudo elements' UI. Get the element using querySelector. Modify the classes using classList.
You can't select pseudo elements in jQuery because they are not part of DOM. But you can add a specific class to the parent element and control its pseudo elements in CSS.
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'; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With