Get Pseudo elements using Javascript

Kaushal Shah
How To's? for Coders
2 min readMay 27, 2017

CSS pseudo-elements are incredibly useful — they allow us to perform a number of other simple tasks while preventing the need for additional HTML elements. To this point, these pseudo-element CSS properties have been unreachable by JavaScript but now there’s a method for getting them!

Assume your CSS looks like:

.element:before {
content: 'NEW';
color: rgb(255, 0, 0);
}

To retrieve the color property of the .element:before, you could use the following JavaScript:

var color = window.getComputedStyle(
document.querySelector('.element'), ':before'
).getPropertyValue('color')

Passing the pseudo-element as the second argument to window.getComputedStyle allows access to said pseudo-element styles! Keep this snippet in your toolbox for years to come -- pseudo-elements will only grow more useful with broader browser support!

Now, for people like me, who mandates to put up a unit test for everything. I’ve been using Protractor for a while and it is AWESOME!. I can do fun stuff like check for the Pseudo elements for ::after and ::before CSS properties.

You can use something like this to execute a script in the browser and grab the values from the element and later assert them against the value of your choice. For instance you would like to check color property of a span class with pseudo element ::after, you can do something like this:

expect(browser.executeScript("return window.getComputedStyle(document.querySelector('.fs-headline.fs-responsive-text>span'), ':after').getPropertyValue('color')")).toEqual('rgb(196, 26, 35)');

Not to be picky here, but make sure you do convert the rgba to it’s corresponding HEX value when cross-checking.

#keepcodingcoolstuff

The topic in itself is a tricky one to get around with a solution and I’d like to callout my source of reference David Walsh for cracking through it. This article is an extension to his findings from https://davidwalsh.name/pseudo-element.

--

--

How To's? for Coders
How To's? for Coders

Published in How To's? for Coders

At How To's, you can find a source highlighting programming hacks, tricks and awesome findings…

Kaushal Shah
Kaushal Shah

Written by Kaushal Shah

“It seems as though inspiration strikes at the most unlikely times”