Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get reference to the ::before or ::after node in JS?

As far as I know, standard JavaScript has no way to get at the ::before or ::after pseudo-elements. Element.children doesn't let you get to it.

I know there has to be a way, at least in Chrome-privileged Firefox add-on code, since it lists every ::before element in the page (and apparently getComputedStyle() works on it too, as you can list all styles of it in inspector, which is written in JavaScript).

Where is this API documented, and is it something that's different and privileged-only in say Firefox and Chrome browser, or something that is on track to be standard soon?

like image 858
NoBugs Avatar asked Sep 20 '25 14:09

NoBugs


1 Answers

The CSS generated content is not part of the DOM, and you wouldn't be able to do much with the ::before/::after pseudo-elements, even if you get at them. The only use-cases I can think of are:

  • Access the CSS computed values on the pseudo-elements. window.getComputedStyle() supports this via an optional 2nd parameter.

  • Enumerate the generated content. You can accomplish this:

    • by using a browser-specific API. In Firefox, the DevTools inspector uses a special interface - inIDeepTreeWalker.
    • or by walking the DOM and checking (for each element) if it has content in its computed style for :before / :after. For example:

      window.getComputedStyle(elt, ':before').content
      
  • Get the "live" value of a counter defined in CSS, like in How to access CSS generated content with JavaScript - see that question for details.

like image 185
Nickolay Avatar answered Sep 22 '25 04:09

Nickolay