Using JavaScript to get CSS values of pseudo elements

June 14th, 2012

If you want to get the CSS property value of any element using JavaScript, you use window.getComputedStyle. This gives you the final value after the page is rendered. So if you wanted to get the width of a div, you’d write something like this:

1
2
var box = document.querySelector('.box');
var boxWidth = window.getComputedStyle(box, null).width;

That’s pretty simple, even if it’s a bit wordy. Obviously, it was named by the same people that came up with querySelector. And if you’re like me, you’ve learned a fair chunk of your JavaScript from doing tutorials or looking at example code. Most of the time when someone uses something like this in a tutorial, they don’t explain everything about it and you might be left wondering what that null is in there. If was important, they’d probably mention something, right?

Turns out we can use that to get syle information from a CSS pseudo element. That might not seem like a big deal, but I use :before and :after all the time to add icons to p tags or div tags and this could come in useful if you’re using JavaScript to position elements and need to take a pseudo element into account.

Leave a Reply

Your email address will not be published. Required fields are marked *