Home >Web Front-end >JS Tutorial >How Can I Select and Manipulate CSS Pseudo-Elements (like ::before and ::after) with JavaScript or jQuery?
Selecting and Manipulating CSS Pseudo-Elements with JavaScript or jQuery
Using CSS pseudo-elements, such as ::before and ::after, can add extra styling to your elements without adding extra content to the DOM. However, selecting and manipulating these pseudo-elements can be challenging.
Selecting Pseudo-Elements with jQuery
jQuery allows you to select pseudo-elements using the same syntax as for regular elements. For example, to select the ::after pseudo-element of the .span class, you would use:
To change the 'foo' content in your example, you can use the jQuery css() method:
Using Vanilla JS
If you prefer to use vanilla JS, you can also select pseudo-elements using the :before and :after selectors. However, they require a more complex syntax than jQuery:
To modify the content, you can use the style.content property:
Manipulating Pseudo-Element Content with jQuery
Another approach is to use data attributes to store the pseudo-element content. In your HTML:
In jQuery, you can then use the hover() method to update the content on hover:
In CSS, you can use the attr() function to access the data-content attribute and set the pseudo-element content:
This allows you to change the pseudo-element content without adding extra markup or overriding the existing CSS rules.
The above is the detailed content of How Can I Select and Manipulate CSS Pseudo-Elements (like ::before and ::after) with JavaScript or jQuery?. For more information, please follow other related articles on the PHP Chinese website!