8

This is a really quick question :)

Just wondering here if its possible for javascript to select objects which aren't part of the DOM... like selecting an :after or :before content created by CSS?

for example...if I have a div and create a box through

div:after{
  content: '.';
  display: block;
  width: 200px;
  height: 200px;
  background: green;
}

I still having difficulties to understand how those elements are created and since they can draw elements on screen but are not part of them DOM, does this mean it's not possible to interact with them?

Cheers

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
zanona
  • 12,345
  • 25
  • 86
  • 141
  • 1
    [Previous question](http://stackoverflow.com/questions/2651739/how-to-access-css-generated-content-with-javascript) – Su' Feb 17 '11 at 16:25

2 Answers2

7

No, you won't be able to interact with them.

They're not part of the DOM, but rather are a manifestation of the style that was assigned.

If you need to add/remove the content, you can use class names.

<div id='myElem' class='withAfter'>some content</div>
div.withAfter:after{
  content: '.';
  display: block;
  width: 200px;
  height: 200px;
  background: green;
}

Then add/remove the class as needed.

user113716
  • 318,772
  • 63
  • 451
  • 440
  • 1
    It's one of the pitfalls of generated content. It's great in theory to be able to tweak the structure via the stylesheet to get things to display nicely, but interacting with it isn't supported. – zzzzBov Feb 17 '11 at 16:36
2

Check out the docs, I see that you cannot modify the properties directly, nor does it appear you can interact with the content created via pseudo-selectors. The best you can do is look at the properties: http://jsfiddle.net/uaN6z/

It looks something like this:

window.getComputedStyle(document.getElementById('test'), ':after')

The only viable way I've see to change it is to alter document style sheet. See this SO answer: Setting CSS pseudo-class rules from JavaScript

Good luck!

Community
  • 1
  • 1
Chris Baker
  • 49,926
  • 12
  • 96
  • 115