Getting CSS pseudo-element properties by Javascript

You probably wonder if you can access CSS pseudo-element's (like ::before or :: after) properties by Javascript.

The answer is yes, you can, but it's tricky :)

Let's assume you have following HTML/CSS


<p id="myid">some content</p>



#myid::after {
  display:block;
  width: 100px;
  height: 40px;
  color: blue;
  content: "Hello world";
}
#myid {
  color: red;
}


Apparently, "#myid::after" is not in the DOM tree, but following trick will allow you to get its properties:


var color = window.getComputedStyle(document.querySelector('#myid'), ':after').getPropertyValue('color')
var content = window.getComputedStyle(document.querySelector('#myid'), ':after').getPropertyValue('content')
console.log(color, content) // outputs the color and content of the pseudo-element

You might find it useful in test automation or some UI interaction manipulation.
  • 0
  • October 21, 2016, 11:13pm
  • t0lkman

Comments (0)

RSS Collapse / Expand

Only registered and authorized users can leave comments. Login or Register