BlogATAhon2021 Entry
Get Pseudo-Elements Using Javascript
by Kaushal Shah
Kaushal Shah
“It seems as though inspiration strikes at the most unlikely times”
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 this:
.element:before {
content: 'NEW';
color: rgb(255, 0, 0);
}
To retrieve the colour 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 the colour property of a span class with pseudo-element ::after, you can do something like this:
expect(browser.executeScript("return window.getComputerStyle(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 its corresponding HEX value when cross-checking.
The original post can be found here.
About Author
Experienced People Manager, Engineer & Tech Evangelist with years of experience developing Softwares and a strong believer in testing ones’ code thoroughly by architecting, designing and developing automated platforms to enable automatic testing via code.
Have delivered products within industry domain namely Media, Retail, Resourcing & IT for both Fortune 500s MNCs and Early Startups. Over the years, have been serving both the Product and Service industries with excellent involvement not just within the development area, but also engaged with more integral management roles to implement newer technologies.