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, the stylesheet has the following rule:
How to change ‘foo’ to ‘bar’ using jQuery?
You could also pass the content to the pseudo element with a data attribute and then use jQuery to manipulate that:
HTML:
jQuery:
CSS:
To prevent the ‘other text’ from showing up, we could combine this like this:
HTML:
jQuery:
CSS:
Add/remove a predetermined class :
In this approach, you’ve already created a class in your CSS with a different :after or :before style. Place this “new” class later in your stylesheet to make sure it overrides:
[ad type=”banner”]You can’t select pseudo elements in jQuery because they are not part of DOM.
But you can add an specific class to the father element and control its pseudo elements in CSS.
jQuery:
CSS:
you could also do:
Here is the way to access :after and :before style properties, defined in css:
[ad type=”banner”]- IF you want to manipulate the ::before or ::after pseudo elements entirely through CSS, you could do it using JavaScript as shown below.
- Notice how the <style> element has an ID, which you can use to remove it and append to it again if your style changes dynamically.
- This way, your element has its style exactly how you want it through CSS, with the help of JS.
- Add a rule to the document with the new content and reference it with a class. depending on what is needed .the class might need an unique id for each value in content.
- Why adding classes or attributes when you can just append a style to head
- Write separate classes attached with psuedo element for each style and then using JavaScript or jQuery toggle between these classes as shown below.
- Inject new styles to the existing document stylesheet directly either via JavaScript and the webpage will automatically reflect the new css.