Read more

How to access before/after pseudo element styles with JavaScript

Arne Hartherz
November 08, 2018Software engineer at makandra GmbH

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

Using getComputedStyle

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

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('#')
Posted by Arne Hartherz to makandra dev (2018-11-08 15:13)