I'm trying to add icons to my navigation (which dynamically changes) via JavaScript.
Here is my code (or JSFiddle):
var icon = document.querySelector('#icon');
icon.setAttribute('data-icon', '†');
#icon:after {
content: attr(data-icon);
}
<div id="icon" data-icon="">
Icon
</div>
But it is not working, why? When tried to edit data-icon
attribute manually, icon appears. Otherwise just unicode of icon.
To insert an icon, add the name of the icon class to any inline HTML element. The <i> and <span> elements are widely used to add icons. All the icons in the icon libraries below, are scalable vector icons that can be customized with CSS (size, color, shadow, etc.)
You can upload your own SVGs, add them to the library, then create a custom font combining FontAwesome with your own icons.
HTML entities don't have any meaning in CSS. If you want to follow that path you need to decode it first:
var icon = document.querySelector('#icon');
var tmp = document.createElement("span");
tmp.innerHTML = '†';
icon.setAttribute('data-icon', tmp.innerText);
#icon:after {
content: attr(data-icon);
}
<div id="icon" data-icon="">
Icon
</div>
... or, alternatively, just type character as-is (as long as your application is written in UTF-8):
var icon = document.querySelector('#icon');
icon.setAttribute('data-icon', '†');
#icon:after {
content: attr(data-icon);
}
<div id="icon" data-icon="">
Icon
</div>
Last but not least, CSS also accepts escape sequences but you need to use the appropriate syntax. This approach, however, does not seem to work for your specific character:
var icon = document.querySelector('#icon');
// Brackets added for visibility, not part of the syntax
icon.setAttribute('data-icon', '(\u0086)(\u2020)');
#icon:after {
content: attr(data-icon);
}
<div id="icon" data-icon="">
Icon
</div>
I presume it's related to the fact that U+2020 'DAGGER' (that works fine) is a regular character but the one you're using U+0086 'START OF SELECTED AREA' (which doesn't show) is a control character. As you mention in a follow-up comment, you're using FontAwesome and such libraries provide custom fonts that map certain code points to display icons (though they normally use private areas to avoid conflicts).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With