1

I recently needed to do Window.getComputedStyle() and Element.getBoundingClientRect() on a pseudo-element ::after to get the exact float pixel values of its position and size since it was positioned absolute from a viewport (vw) relative positioned input and it was too confusing for me to guess.

The way I did to do that was with $0 (I'm using Google Chrome's Developer Tools console) which returns the currently-inspected element in the page.

window.getComputedStyle($0);
$0.getBoundingClientRect();

My question is how can a pseudo-element be targeted with JavaScript?

I tried to get it by using document.querySelector() but got no success:

document.querySelector('::after');
document.querySelector('*::after');
document.querySelector('input::after');
document.querySelector('input > *');
document.querySelector('input[type=radio]::after');

After that I searched but the only thing that I found was a way to get the properties:

window.getComputedStyle(document.querySelector('input'), '::after').getPropertyValue('color');

Source

user7393973
  • 2,270
  • 1
  • 20
  • 58
  • I closed this even though the related post is for JQuery. The answers/comments in that post explain that it can't be done directly, but do talk about work arounds. – Scott Marcus Jan 31 '18 at 17:05
  • @ScottMarcus I guess there's really no way since the workarounds are to change/get/set the properties. So there's no way to for example [log](https://developer.mozilla.org/en-US/docs/Web/API/Console/log) `::after` as if it was an element just like it does with `console.log($0);`. – user7393973 Jan 31 '18 at 17:29

0 Answers0