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 jQuery?
In the line of what Christian suggests, you could also do:
Here is the way to access :after and :before style properties, defined in css:
Someone else commented on appending to the head element with a full style element and that's not bad if you're only doing it once but if you need to reset it more than once you'll end up with a ton of style elements. So to prevent that I created a blank style element in the head with an id and replace the innerHTML of it like this:
Then the JavaScript would look like this:
Now in my case I needed this to set the height of a before element based on the height of another and it will change on resize so using this I can run
setHeight()
every time the window is resized and it will replace the<style>
properly.Hope that helps someone who was stuck trying to do the same thing.
We can also rely on CSS custom properties (variables) in order to manipulate pseudo-element. We can read in the specification that:
Considering this, the idea is to define the custom property within the element and the pseudo-element will simply inherit it; thus we can easily modify it.
Please note that CSS variables might not be available in all browsers you consider relevant (e.g. IE 11): https://caniuse.com/#feat=css-variables
1) Using inline style:
2) Using CSS and classes
3) Using javascript
4) Using jQuery
It can also be used with complex values:
I'm always adding my own utils function, which looks like this.
or make use of ES6 Features:
There are many answers here but no answer helps to manipulate the css of
:before
or:after
, not even the accepted one.Here is how I propose to do it. Lets suppose your HTML is like this:
And then you are setting its :before in CSS and designing it like:
Please notice I also set
content
attribute in element itself so that you can take it out easily later. Now there is abutton
clicking on which, you want to change the color of :before to green and its font-size to 30px. You can achieve that as follows:Define a css with your required style on some class
.activeS
:Now you can change :before style by adding the class to your :before element as follows:
If you just want to get content of
:before
, it can be done as:Ultimately if you want to dynamically change
:before
content by jQuery, You can achieve that as follows:Clicking on above "changeBefore" button will change
:before
content of#something
into '22' which is a dynamic value.I hope it helps