1

This doesn't work, but it shows you what I want to do:

$(this+":after").css('content', 'something');

Basically, I want my function to dynamically add an :after element to various matched elements.

Is there a correct way to do this?

emersonthis
  • 32,822
  • 59
  • 210
  • 375

2 Answers2

3

You cannot use the pseudo-elements :after and :before in JavaScript (and jQuery is JavaScript, too!).

However, you can simply .append() something:

$(this).append('something');

If that's not what you want, you could put this in your CSS:

something:after { content: attr(data-after); }

Then you can use .attr('data-after', 'whatever') to modify the text used in the :after "element". Note that you cannot use .data('after', 'whatever') as it only reads attributes but never sets them.

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
3

$(this).after('content'); is what you're looking for

http://api.jquery.com/after/

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
  • This places the content after the element, but not within it, so it works completely differently from using an `:after` pseudo-element. – BoltClock Apr 18 '12 at 19:41
  • That is true, but it is unclear from the OP's statement exactly what he wants to do. If he wants it within the element we can cover that too. – Jay Blanchard Apr 18 '12 at 19:42
  • I am trying to replicate the behavior of the css :after, so inside would be better. If it helps, what I'm actually trying to do is place the new element "behind" the original one. – emersonthis Apr 18 '12 at 20:18
  • $(this).appendTo('content'); will be what you want then as this applies the 'content' inside. – Jay Blanchard Apr 18 '12 at 20:26