To select and manipulate CSS pseudo-elements like ::before and ::after using JavaScript or jQuery, you can employ a few different techniques.
Manipulating Content Using jQuery
jQuery allows you to retrieve and manipulate the content of pseudo-elements like this:
// Get the content of ::after for an element with class "span" var content = $('.span::after').text();
To change the content, simply assign a new value:
// Change the content of ::after for elements with class "span" $('.span::after').text('bar');
Manipulating Content with Data Attributes
Alternatively, you can pass content to pseudo-elements using data attributes and jQuery:
<!-- Element with a data attribute --> <span data-content="foo">foo</span>
// Get the content from the data attribute var content = $('span').attr('data-content'); // Manipulate the pseudo-element content $('.span::after').text(content);
To change the content on hover, you can combine this approach with event handlers:
$('span').hover(function() { // Change the content of ::after on hover $(this).attr('data-content', 'bar'); });
span::after { content: attr(data-content) /* Combine this with seucolega's solution */ ' any other text you may want'; }
By using these techniques, you can dynamically control the content and appearance of pseudo-elements in your web applications.
The above is the detailed content of How Can I Select and Manipulate CSS Pseudo-elements (::before, ::after) with JavaScript/jQuery?. For more information, please follow other related articles on the PHP Chinese website!