Rick Viscomi
Rick Viscomi

Reputation: 8852

Accessing the style property "content" on a :before pseudo selector

I have about 250 font icons on a page and I would like to programmatically extract the Unicode values for each icon.

A typical icon has corresponding CSS like this:

.icon-play:before {
    content: "\f04b";
}

What I've tried so far...

document.querySelectorAll('[class^=icon-]') to access the icons (call each one i for now). i.style to try to access the style object. The problem is that the i.style.content value is empty.

I've also tried to access the content this way document.querySelectorAll('[class^=icon-]:before') but this produces an empty result.

Any help is appreciated. Thanks.

Upvotes: 0

Views: 660

Answers (1)

Brett Zamir
Brett Zamir

Reputation: 14345

Here you go:

var is = document.querySelectorAll('[class^=icon-]');
[].forEach.call(is, function (i) {
    console.log(
        window.getComputedStyle(i, ':before').content.slice(1, -1) // Strip off surrounding quotes
    );
});

JSFiddle (with some added complexity in order to display the results visually)

As far as extracting the Unicode values, you didn't specify your desired format (unless you just meant grabbing the string contents), but if you need the code points, you can apply charCodeAt() to each character of the string above to find out their code points and do with them as you wish.

Upvotes: 1

Related Questions