Font Awesome - Changing SVG icons programmatically

Share

Font Awesome is the most famous icon library for web development. SVG is a good performant option to render icons when you are using only a few icons.

While working on the article, Custom Event with RxJS, I learned that Font Awesome replaces an icon tag with an SVG upon rendering, which makes changing the icon tricky.

This,

<i></i>

changes to this,

<svg
 
  aria-hidden="true"
  focusable="false"
  data-prefix="far"
  data-icon="circle"
  role="img"
  xmlns="http://www.w3.org/2000/svg"
  viewBox="0 0 512 512"
  data-fa-i2svg=""
>
  . .
</svg>

Things to note:

  • dot is a custom class. Font Awesome made this custom class as one of the classes of rendered SVG. This mechanism is helpful to target SVG.

  • far became the data-prefix of SVG.

  • circle became data-icon.

Technique

  1. Fetch the SVG through class/id, which is added in the icon tag.
  2. Change data-prefix or data- icon according to your requirement.
// 1. Fetch SVG
let dot = document.querySelector('.dot')
// 2. Change data-prefix or data-icon
let icon = dot.getAttribute('data-prefix') === 'far' ? 'fas' : 'far'
dot.setAttribute('data-prefix', icon)
Attributions:
  1. undefined by undefined