How to Get Content of ::after Pseudo-Element Using JavaScript?

In JavaScript, to get the content property value, as specified by ::after pseudo-element, you can use the window.getComputedStyle() method. It exposes the CSSStyleDeclaration object (as read-only), from which you can access the style information of ::after pseudo-element.

For example:

    <a id="foo" href="#">foobar</a>
a::after { content: ' [' attr(href) ']'; }
const element = document.getElementById('foo');
const styles = window.getComputedStyle(element, '::after');
const content = styles.content;

console.log(content); // ' [#]'

If the content property is not defined, then its computed value "none" is returned.

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.