Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
fontawesome
svg
frontend
communitycreator

Font Awesome - Changing SVG icons programmatically

Puneet Sapra

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 class="dot far fa-circle"></i>

changes to this,

<svg
  class="svg-inline--fa fa-circle fa-w-16 dot"
  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)

RELATED TAGS

javascript
fontawesome
svg
frontend
communitycreator
RELATED COURSES

View all Courses

Keep Exploring