Home > Web Front-end > JS Tutorial > How Can I Select and Manipulate CSS Pseudo-elements (::before, ::after) with JavaScript/jQuery?

How Can I Select and Manipulate CSS Pseudo-elements (::before, ::after) with JavaScript/jQuery?

Mary-Kate Olsen
Release: 2024-12-21 08:37:10
Original
708 people have browsed it

How Can I Select and Manipulate CSS Pseudo-elements (::before, ::after) with JavaScript/jQuery?

Selecting and Manipulating CSS Pseudo-Elements with JavaScript/jQuery

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();
Copy after login

To change the content, simply assign a new value:

// Change the content of ::after for elements with class "span"
$('.span::after').text('bar');
Copy after login

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>
Copy after login
// Get the content from the data attribute
var content = $('span').attr('data-content');

// Manipulate the pseudo-element content
$('.span::after').text(content);
Copy after login

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');
});
Copy after login
span::after {
  content: attr(data-content) /* Combine this with seucolega's solution */ ' any other text you may want';
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template