Switch between icons when using FontAwesome 5.0 SVG Framework

Verified with FA 5.0.2

I modified the original documentation found on Font-Awesome's website here. The selector on their website wasn't selecting the proper element, so we need to modify the attribute.

HTML

<div class='icon'><i class='far fa-minus-square'></i></div>

The class of the div doesn't really matter so much as we can change it. Looking at the javascript, we are using the element to find the svg and specifically, we are looking for the data-icon attribute. Once we know the data attribute, we can change it every time it is clicked.

So in this case, it starts off with the minus-square. If the icon is the minus-square, it changes it to the plus-square. If it is not the plus-square, it will change it to the minus-square.

JQuery

  document.addEventListener('DOMContentLoaded', function () {
    $('.icon').on('click', function () {
      if ($(this).find('svg').attr('data-icon') == 'minus-square' ) {
        $(this).find('svg').attr('data-icon', 'plus-square');
      } else {
        $(this).find('svg').attr('data-icon', 'minus-square');
      };
    });
  });

Font Awesome 5.0.0 has just been released and the migration from 4.7 to 5.0 wrecked up my javascript/jquery to change a "fa-star-o" icon to "fa-star" when the user clicks on it.

I managed to fix it so I wanted to share with you these two tips:

The icon in HTML:

<i class="foo fas fa-star"></i>

1) Change icon with jQuery (from "star" to "alarm-clock" and vice versa):

var icon = $('.foo');
var icon_fa_icon = icon.attr('data-icon');

if (icon_fa_icon === "alarm-clock") {
    icon.attr('data-icon', 'star');
} else {
    icon.attr('data-icon', 'alarm-clock');
}

2) Change icon-style with jQuery (from 'fas' to 'far'):

var icon = $('.foo');
var icon_fa_prefix = icon.attr('data-prefix');

if (icon_fa_prefix === 'fas') {
    icon.attr('data-prefix', 'far');

} else {
    icon.attr('data-prefix', 'fas');
}

Hope that helps anyone with the same issue.