patternjavascriptCritical
Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)
Viewed 0 times
jqueryandpseudousingsuchcssselectingbeforeafterjavascript
Problem
Is there any way to select/manipulate CSS pseudo-elements such as
For example, my stylesheet has the following rule:
How can I change 'foo' to 'bar' using vanilla JS or jQuery?
::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?
Solution
You could also pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:
In HTML:
In jQuery:
In CSS:
If you want to prevent the 'other text' from showing up, you could combine this with seucolega's solution like this:
In HTML:
In jQuery:
In CSS:
In HTML:
fooIn 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:
fooIn 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';
}
Code Snippets
<span>foo</span>$('span').hover(function(){
$(this).attr('data-content','bar');
});<span>foo</span>$('span').hover(function(){
$(this).addClass('change').attr('data-content','bar');
});Context
Stack Overflow Q#5041494, score: 786
Revisions (0)
No revisions yet.