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?
You may create a fake property or use an existing one and inherit it in the pseudo-element's stylesheet.
It seems it doesn't work for "content" property :(
You can use my plugin for this purpose.
JQuery:
The values should be specified, as in the normal function of jQuery.css
In addition, you can also get the value of the pseudo-element parameter, as in the normal function of jQuery.css:
JS:
GitHub: https://github.com/yuri-spivak/managing-the-properties-of-pseudo-elements/
Thank you all! i managed to do what i wanted :D http://jsfiddle.net/Tfc9j/42/ here take a look
i wanted to have the opacity of an outer div to be different from the opacity of the internal div and that change with a click somwewhere ;) Thanks!
You could also pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:
In HTML:
In jQuery:
In CSS:
If you want to prevent the 'other text' from showing up, you could combine this with seucolega's solution like this:
In HTML:
In jQuery:
In CSS:
Although they are rendered by browsers through CSS as if they were like other real DOM elements, pseudo-elements themselves are not part of the DOM, because pseudo-elements, as the name implies, are not real elements, and therefore you can't select and manipulate them directly with jQuery (or any JavaScript APIs for that matter, not even the Selectors API). This applies to any pseudo-elements whose styles you're trying to modify with a script, and not just
::before
and::after
.You can only access pseudo-element styles directly at runtime via the CSSOM (think
window.getComputedStyle()
), which is not exposed by jQuery beyond.css()
, a method that doesn't support pseudo-elements either.You can always find other ways around it, though, for example:
Applying the styles to the pseudo-elements of one or more arbitrary classes, then toggling between classes (see seucolega's answer for a quick example) — this is the idiomatic way as it makes use of simple selectors (which pseudo-elements are not) to distinguish between elements and element states, the way they're intended to be used
Manipulating the styles being applied to said pseudo-elements, by altering the document stylesheet, which is much more of a hack
Why adding classes or attributes when you can just append a
style
to head