6

I need to dynamically create my CSS styles for my elements. However, I need to have :after in CSS and I have heard that you cannot modify this in jQuery.

Is this true? Is there anyway around this?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
user1083320
  • 1,836
  • 8
  • 22
  • 29

3 Answers3

15

You can generate a <style> tag and insert it into the <head>:

http://jsfiddle.net/PrBHF/

$("head").append($('<style>div:after { content: " World" }</style>'));
thirtydot
  • 224,678
  • 48
  • 389
  • 349
Ates Goral
  • 137,716
  • 26
  • 137
  • 190
  • This does not work in all browsers, specially Internet Explorer. – ShankarSangoli Feb 06 '12 at 20:25
  • There are alternative methods here: http://stackoverflow.com/questions/311052/setting-css-pseudo-class-rules-from-javascript – thirtydot Feb 06 '12 at 20:25
  • @ShankarSangoli: This answer works in IE8/9. It doesn't work in any lower version due to `:after` not being supported. – thirtydot Feb 06 '12 at 20:26
  • 1
    Regarding browser support: Since the question is about `:after` to begin with, it's implicit that browser support is not part of the question/answer. – Ates Goral Feb 06 '12 at 23:03
  • @ShankarSangoli call me whatever you want but I stopped caring about Internet Explorer simply not doing what usually works well in all other browsers. Especially old versions. If people still use IE6 and still ride bicycle without helmet, let them. I don't care anymore. – Chris S. Oct 04 '18 at 13:16
6

Why create css using javascrript?

Have the required styles in a css class and then apply the class using jQuery by using addClass method.

ShankarSangoli
  • 69,612
  • 13
  • 93
  • 124
5

Is this true?

Yes. Pseudo-elements created with :after are not part of the DOM and therefore cannot be selected.

Is there anyway around this?

No. Unless you do it without :after (use an actual element, then you can select it/bind events to it).

Edit

Having re-read your question, I think you're actually asking if you can apply :after styles to an element with jQuery. The answer is still no, although you can use addClass to add a new class to the element and define :after styles for that class name.

Edit again

When I've said "no", it seems I'm not entirely correct... see @AtesGorals answer for a nice workaround.

James Allardice
  • 164,175
  • 21
  • 332
  • 312