Home > Web Front-end > JS Tutorial > How Can I Dynamically Change CSS Pseudo-Element Content with JavaScript or jQuery?

How Can I Dynamically Change CSS Pseudo-Element Content with JavaScript or jQuery?

Patricia Arquette
Release: 2024-12-21 20:32:03
Original
370 people have browsed it

How Can I Dynamically Change CSS Pseudo-Element Content with JavaScript or jQuery?

Manipulating CSS Pseudo-Elements with JavaScript and jQuery

The ability to dynamically modify the content of CSS pseudo-elements (e.g., ::before, ::after) using JavaScript or jQuery can be highly useful.

jQuery Solution

To change the content of a pseudo-element using jQuery, you can use the following steps:

  1. Select the element to which the pseudo-element is attached.
  2. Use the :after or :before selector to target the pseudo-element.
  3. Set the content property to the desired value.

For example, to modify the ::after pseudo-element with content 'foo' to display 'bar':

$('span').find(':after').text('bar');
Copy after login

Vanilla JavaScript Solution

In vanilla JavaScript, you can manipulate pseudo-elements using the window.getComputedStyle() method and the ::after or ::before selector appended to the element's style property.

For instance, to achieve the same result as the jQuery example above:

document.querySelector('span').style['::after'].content = '"bar"';
Copy after login

Alternative Approach Using Data Attributes

An alternative approach is to use data attributes to store the desired content and then use jQuery to modify it dynamically.

For example, add a data attribute to the span element:

<span data-content="foo"></span>
Copy after login

Then, in jQuery, set the attr() of the pseudo-element to manipulate its content:

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

In CSS, define the pseudo-element with its content coming from the data attribute:

span:after {
  content: attr(data-content);
}
Copy after login

The above is the detailed content of How Can I Dynamically Change CSS Pseudo-Element Content with JavaScript or 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