Home > Web Front-end > JS Tutorial > Can JavaScript and jQuery Manipulate CSS Pseudo-elements like ::before and ::after?

Can JavaScript and jQuery Manipulate CSS Pseudo-elements like ::before and ::after?

Linda Hamilton
Release: 2024-12-20 10:29:09
Original
636 people have browsed it

Can JavaScript and jQuery Manipulate CSS Pseudo-elements like ::before and ::after?

Selecting and Manipulating CSS Pseudo-Elements Using JavaScript and jQuery

Can CSS pseudo-elements like ::before and ::after (both old and new versions) be selected and manipulated using jQuery?

Using jQuery's .css() Method

Assuming the following CSS rule in the stylesheet:

.span::after { content: 'foo'; }
Copy after login

To change 'foo' to 'bar' using vanilla JavaScript or jQuery, you can use the .css() method.

Vanilla JavaScript:

const element = document.querySelector('.span');
element.style.content = 'bar';
Copy after login

jQuery:

$('.span').css('content', 'bar');
Copy after login

Using Data Attributes

Another method involves passing the content to the pseudo-element using a data attribute and manipulating it with jQuery.

In HTML:

<span>foo</span>
Copy after login
Copy after login

In jQuery:

$('span').hover(function() {
  $(this).attr('data-content', 'bar');
});
Copy after login

In CSS:

span:after {
  content: attr(data-content) ' any other text you may want';
}
Copy after login

To prevent the additional text from showing up, seucolega's solution can be combined with this approach.

In HTML:

<span>foo</span>
Copy after login
Copy after login

In jQuery:

$('span').hover(function() {
  $(this).addClass('change').attr('data-content', 'bar');
});
Copy after login

In CSS:

span.change:after {
  content: attr(data-content) ' any other text you may want';
}
Copy after login

These methods provide flexibility in selecting and modifying the content of CSS pseudo-elements using either JavaScript or jQuery.

The above is the detailed content of Can JavaScript and jQuery Manipulate CSS Pseudo-elements like ::before and ::after?. For more information, please follow other related articles on the PHP Chinese website!

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