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
Linda HamiltonOriginal
2024-12-20 10:29:09637browse

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'; }

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';

jQuery:

$('.span').css('content', 'bar');

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>

In jQuery:

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

In CSS:

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

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

In HTML:

<span>foo</span>

In jQuery:

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

In CSS:

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

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:
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