FontAwesome - Changing SVG icons programmatically

FontAwesome is the most famous icon library. When you only need a few icons, SVG is a fantastic alternative for rendering them.

While working on Article: Custom Event with RxJS, I discovered that FontAwesome renders the icon tag as SVG, making changing the icon difficult. Changing the class of <i> tag alone is not a solution. To alter the icon programmatically, you must first understand “how it is rendered.”

Rendering of icon

<i class="dot far fa-circle"></i>

It’s worth noting that dot isn’t a FontAwesome-specific class. Any class can be added; it is used to demonstrate a technique that you will learn about in the subsequent section. The SVG code for the aforementioned “icon tag” is as follows:

  class="svg-inline--fa fa-circle fa-w-16 dot"
  viewBox="0 0 512 512"
  . .

Elements of SVG

  • dot is a custom class; FontAwesome made this custom class as one of the classes of rendered SVG. This mechanism is helpful to target SVG.
  • far became data-prefix of SVG.
  • circle became data-icon.


  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
// We added `dot` as custome class <i class="dot far fa-circle"></i>
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)

In Action

Be Updated

Only articles are shared on Medium