FontAwesome - Changing SVG icons programmatically

font-awesome javascript

FontAwesome is the most famous icon library. SVG is one good performant option to render icons when you are using a few icons.

While working on Article: Custom Event with RxJS; I learnt that FontAwesome replaces icon tag with SVG on rendering, which makes changing the icon tricky.

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

Result in

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

Note down:

  • 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
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

This site uses third-party cookies to gather website usage and performance data.