How to Get CSS Values of Pseudo Elements with Javascript

Use-Cases of this Tutorial

  • Find values of CSS properties of a pseudo element with Javascript.

To get the current CSS rules of any pseudo element, the window.getComputedStyle method is used.

This method accepts 2 parameters :

  • First parameter is the DOM element whose pseudo-element we need.
  • Second parameter specifies the pseudo element to match — ::before, ::after, ::selection etc.
    (if this second parameter is ignored, then the CSS properties of the DOM element specified in the first parameter will be returned)
<div id="container">Content</div>
#container {
    position: relative;
}

#container::after {
    content: "X";
    top: 0;
    right: 0;
    position: absolute;
    color: rgb(64, 64, 64);
}
// main DOM element
var element = document.querySelector("#container");

// CSS styles of the "::after" pseudo-element
var style_rules = window.getComputedStyle(element, "::after");

// "content" CSS propery
// "X"
console.log(style_rules.content);

// "color" CSS propery 
// "rgb(64, 64, 64)"
console.log(style_rules.color);

window.getComputedStyle() returns all CSS properties of the element as an object. Individual CSS properties can be read by specifying the camel-case notation of the property.

How to Get Current Value of a CSS Property in Javascript