0

How do I set CSS properties of .anyclass:before or .anyclass:after via javascript?

fancy
  • 48,619
  • 62
  • 153
  • 231
  • Do you want to add it as a general rule to the page? – Yoshi Dec 06 '11 at 15:06
  • `:before` and `:after` are not properties, they are CSS selectors. Therefore you cannot set them on some element, you can only add rules with such selectors to a stylesheet. – Jon Dec 06 '11 at 15:08
  • :( they are so useful though. setting properties on them programmatically would be wonderful. – fancy Dec 06 '11 at 15:09

2 Answers2

2

Expanding on my comment:

:before and :after are not properties, they are CSS selectors. Therefore you cannot set them on some element, you can only add rules with such selectors to a stylesheet.

If you want to add DOM nodes before or after all elements that match a given selector with jQuery, you can use the before and after methods respectively.

If you want to add CSS rules to the current page, you can use the DOM level 2 CSSStyleSheet interface. A minimal example would look like this:

// Note: this is sample code. Do not use it blindly in your own page.
document.styleSheets[0].insertRule(".foo:before { /* something */ }", 0);

See the MDN documentation for insertRule for more example code.

Jon
  • 428,835
  • 81
  • 738
  • 806
0

Only by modifying the stylesheet itself. Since they aren't real elements you cannot modify their inline style (because they don't have any).

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335