How to Access CSS Properties of an HTML Element :after Using JavaScript?

Estimated read time 1 min read

To access CSS properties of an HTML element’s :after pseudo-element using JavaScript, you can use the window.getComputedStyle() method. The getComputedStyle() method returns an object that represents the computed style of an element, which includes the values of all CSS properties, including those applied to pseudo-elements like :after.

Here’s an example of how you can use getComputedStyle() to access the background-color property of an element’s :after pseudo-element:

<style>
  .example:after {
    content: "";
    display: block;
    background-color: red;
    width: 100px;
    height: 100px;
  }
</style>

<div class="example"></div>

<script>
  var example = document.querySelector(".example");
  var style = window.getComputedStyle(example, ":after");
  var backgroundColor = style.getPropertyValue("background-color");
  console.log(backgroundColor);
</script>

In this example, the getComputedStyle() method is used to retrieve the computed style of the .example element’s :after pseudo-element. The getPropertyValue() method is then used to retrieve the value of the background-color property, which is logged to the console.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply