Selecting and Manipulating CSS Pseudo-Elements Using JavaScript and jQuery
Can CSS pseudo-elements like ::before and ::after (both old and new versions) be selected and manipulated using jQuery?
Using jQuery's .css() Method
Assuming the following CSS rule in the stylesheet:
.span::after { content: 'foo'; }
To change 'foo' to 'bar' using vanilla JavaScript or jQuery, you can use the .css() method.
Vanilla JavaScript:
const element = document.querySelector('.span'); element.style.content = 'bar';
jQuery:
$('.span').css('content', 'bar');
Using Data Attributes
Another method involves passing the content to the pseudo-element using a data attribute and manipulating it with jQuery.
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'; }
To prevent the additional text from showing up, seucolega's solution can be combined with this approach.
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'; }
These methods provide flexibility in selecting and modifying the content of CSS pseudo-elements using either JavaScript or jQuery.
The above is the detailed content of Can JavaScript and jQuery Manipulate CSS Pseudo-elements like ::before and ::after?. For more information, please follow other related articles on the PHP Chinese website!