Appearance
How to Select and Manipulate CSS pseudo-elements using jQuery
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
javascript
$('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
css
span::after {
content: attr(data-content) 'other text';
}Here is an example:
JavaScript jQuery select and manipulate the CSS pseudo elements
html
<!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 attr() CSS function may be used with any CSS property, but the support for the properties other than content is experimental. The attr() 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 hover() 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 mouseenter() and mouseleave() methods instead.