Posted almost 2 years ago. Visible to the public.

How to access before/after pseudo element styles with JavaScript

Accessing pseudo elements via JavaScript or jQuery is often painful/impossible. However, accessing their styles is fairly simple.

Using getComputedStyle

First, find the element in question.

let element = document.querySelector('.my-element') // or $('.my-element').get(0) when using jQuery

Next, use JavaScript's getComputedStyle. It takes an optional 2nd argument to filter for pseudo elements.

let style = window.getComputedStyle(element, '::before') let color = style.getPropertyValue('background-color')

The returned color will be a string with a color value like "rgb(253, 126, 20)".

Bonus: Hex color strings

If you want to convert that to a hex color, here are two solutions.


Modern JavaScript (ES2017+) can do it like this:

let hexColor = rgbColor .match(/(\d+), (\d+), (\d+)/) .slice(1, 4) .map((number) => { return Number(number).toString(16).padStart(2, '0') }) .join('') .replace(/^/, '#')


My use case was comparing colors in an integration test, so I used JS to get the pseudo element's style via Selenium, and then processed it in my Ruby code like so:

hex_color = rgb_color .match(/(\d+), (\d+), (\d+)/) .captures .map { |number| number.to_i.to_s(16).rjust(2, '0') } .join .prepend('#')

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Arne Hartherz
Last edit:
almost 2 years ago
by Arne Hartherz
selenium, capybara, webdriver, chrome, firefox
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Arne Hartherz to makandra dev
This website uses short-lived cookies to improve usability.
Accept or learn more