How to Select and Manipulate CSS pseudo-elements using jQuery
Read this tutorial and learn the simplest and fastest way of selecting and manipulating the CSS pseudo elements using some jQuery and CSS methods.
To change the content of CSS pseudo-elements such as ::before and ::after, you can use jQuery to update a data attribute on the target element, which CSS then reads via the attr() function. This approach allows you to dynamically change pseudo-element content without directly manipulating the pseudo-element itself:
In jQuery:
JavaScript jQuery select and manipulate the CSS pseudo elements
$('span').on('mouseenter', function () {
$(this).addClass('change').attr('data-content', 'come');
}).on('mouseleave', function () {
$(this).removeClass('change').attr('data-content', '');
});In CSS:
JavaScript jQuery select and manipulate the CSS pseudo elements
span::after {
content: attr(data-content) 'other text';
}Here is an example:
JavaScript jQuery select and manipulate the CSS pseudo elements
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<style>
span.change:after {
content: attr(data-content) ' to W3Docs!';
}
</style>
</head>
<body>
<p>Hover over Wel</p>
<span>Wel</span>
<script>
$(document).ready(function() {
$('span').on('mouseenter', function() {
$(this).addClass('change').attr('data-content', 'come');
}).on('mouseleave', function() {
$(this).removeClass('change').attr('data-content', '');
});
});
</script>
</body>
</html>The attr() Function
The <kbd class="highlighted">attr()</kbd> CSS function may be used with any CSS property, but the support for the properties other than content is experimental. The <kbd class="highlighted">attr()</kbd> function is used to get the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements and returns the value of the attribute on the originating element of pseudo-element.
The hover() Method
The <kbd class="highlighted">hover()</kbd> method is deprecated and has been removed in jQuery 3.5. It previously specified two functions to run when the mouse pointer hovers over the selected elements by binding handlers for both the mouseenter and mouseleave events. If only one function was defined, it ran for both events. For modern jQuery, use the <kbd class="highlighted">mouseenter()</kbd> and <kbd class="highlighted">mouseleave()</kbd> methods instead.