How to access before/after pseudo element styles with JavaScript

Posted . Visible to the public.

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.

JavaScript

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(/^/, '#')

Ruby

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('#')
Arne Hartherz
Last edit
Arne Hartherz
Keywords
selenium, capybara, webdriver, chrome, firefox
License
Source code in this card is licensed under the MIT License.
Posted by Arne Hartherz to makandra dev (2018-11-08 14:13)