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

Find out how to get content value of ::before pseudo-element in JavaScript

In JavaScript, to get the content property value, as specified by ::before 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 ::before pseudo-element.

For example, you can add "#" before all local links like so:

<div>
    <a id="foo" href="#">foobar</a>
</div>
a[href^="#"]::before { content: '#'; }

You can retrieve the content property value (added via ::before), like so:

const element = document.getElementById('foo');
const styles = window.getComputedStyle(element, '::before');
const content = styles.content;

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

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


Hope you found this post useful. It was published . Please show your love and support by sharing this post.