Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting and manipulating CSS pseudo-elements such as ::before and ::after using javascript (or jQuery)

Is there any way to select/manipulate CSS pseudo-elements such as ::before and ::after (and the old version with one semi-colon) using jQuery?

For example, my stylesheet has the following rule:

.span::after{ content:'foo' } 

How can I change 'foo' to 'bar' using vanilla JS or jQuery?

like image 478
JBradwell Avatar asked Feb 18 '11 12:02

JBradwell


People also ask

When would you use the :: before or :: after pseudo-element in your CSS?

Special welcome offer: get $100 of free credit. CSS ::before and ::after pseudo-elements allow you to insert “content” before and after any non-replaced element (e.g. they work on a <div> but not an <input> ). This effectively allows you to show something on a web page that might not be present in the HTML content.

How do you manipulate pseudo elements in JavaScript?

In general, if we want to change anything in pseudo elements through JavaScript, we do it in the following way: Create CSS classes on element, which will change pseudo elements' UI. Get the element using querySelector. Modify the classes using classList.

Can you select pseudo-element in JavaScript?

You can't select pseudo elements in jQuery because they are not part of DOM. But you can add a specific class to the parent element and control its pseudo elements in CSS.


1 Answers

You could also pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:

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

If you want to prevent the 'other text' from showing up, you could combine this with seucolega's solution like this:

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'; } 
like image 96
Nick Kline Avatar answered Oct 11 '22 10:10

Nick Kline