A version of getting the character that includes a cache so we don't have to keep creating and removing elements for each lookup:
Usage
const unicodeCharacter = getIconUnicode("fas fa-arrow-up");
Function
I put this in a file called utils.js or utils.ts and export the function getIconUnicode()
however you can do it any way you like as long as you can call the function.
ES6
const iconUnicodeCache = {};
const getIconUnicode = (iconClass) => {
if (iconUnicodeCache[iconClass]) return iconUnicodeCache[iconClass];
const tempElement = document.createElement("i");
tempElement.className = iconClass;
document.body.appendChild(tempElement);
const character = window.getComputedStyle(tempElement, ':before').getPropertyValue('content').replaceAll(`"`, "");
tempElement.remove();
if (character) {
iconUnicodeCache[iconClass] = character;
}
return character;
};
TypeScript
const iconUnicodeCache: {[key: string]: string} = {};
const getIconUnicode = (iconClass: string): string => {
if (iconUnicodeCache[iconClass]) return iconUnicodeCache[iconClass];
const tempElement = document.createElement("i");
tempElement.className = iconClass;
document.body.appendChild(tempElement);
const character = window.getComputedStyle(tempElement, ':before').getPropertyValue('content').replaceAll(`"`, "");
tempElement.remove();
if (character) {
iconUnicodeCache[iconClass] = character;
}
return character;
};