4

Possible Duplicate:
Manipulating CSS :before and :after pseudo-elements using jQuery

I would like to the jQuery equivalent this CSS code:

p:before {
   content: 'Intro!';
}

I've naively tried $('p:before').css('content', 'Intro!'); but it doesn't work.

How can I do pseudo-element CSS modifications using jQuery?

Community
  • 1
  • 1
Randomblue
  • 112,777
  • 145
  • 353
  • 547

2 Answers2

8

You can't.

1) The selector, p:before, is not just a selector -- the psuedo element defines functionality that does not affect the actual selection. What is jQuery supposed to return, all p tags? That's all $(...) does -- it returns a bunch of elements that match your selector. jQuery (Sizzle/querySelectorAll) doesn't know how to fetch :before...

2) Psuedo-element/class behaviour is not available via JS APIs either.

The only way to do something like this, dynamically via JS, would be to create a <style> element, like so:

$('<style>p:before{content:"intro";}</style>').appendTo('head');

May I ask why you want to do this in the first place?

James
  • 109,676
  • 31
  • 162
  • 175
  • The reason I want this is to have an overlay on a specific element, with that specific element changing over time. Please see [this](http://stackoverflow.com/questions/7731523/doing-overlays-without-an-empty-div) question. – Randomblue Oct 11 '11 at 20:14
2

You can do this:

$(document).append($("<style>p:before{ content: 'Intro!' } </style>"));
Tarcísio Júnior
  • 1,239
  • 7
  • 15