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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)