How to Select and Manipulate CSS pseudo-elements using jQuery

To select and manipulate CSS pseudo elements such as ::before and ::after, you can use the hover() method in a way that will prevent the “other text” from showing up. Firstly, pass the content to the pseudo element with a data attribute and then use jQuery to manipulate it:

In jQuery:

$('span').hover(function () {
  $(this).addClass('change').attr('data-content', 'come');


span: after {
  content: attr(data - content)
  'other text';

Here is an example:

<!DOCTYPE html>
    <title>Title of the Document</title>
    <script src=""></script>
      span.change:after {
        content: attr(data-content) ' to W3Docs!';
    <p>Hover over Wel</p>
      $(document).ready(function() {
          $('span').hover(function() {
              $(this).addClass('change').attr('data-content', 'come');

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 specifies two functions to run when the mouse pointer hovers over the selected elements. It binds handlers for both the mouseenter and mouseleave events. If only one function is defined, it will be run for both the mouseenter and mouseleave events.

Do you find this helpful?

Related articles