Search code examples
javascriptjqueryfont-awesomefont-awesome-5

Change all font awesome 5 icons with a specific class to another FA icon - JS/SVG


Lets say i have 3 FA icons:

<i class="fas fa-circle"></i>
<i class="fas fa-circle"></i>
<i class="fas fa-circle"></i>

I want to change all of those to:

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

This means i am modifying all of the prefix of those icons so that they change from solid to regular.

Before in FA 4.X i could just get all icons by their class name and switch their classes like so:

var icons = $(".icon");
icons.removeClass("fa-circle");
icons.addClass("fa-circle-o");

But now that they are SVG's i don't know how i can get them all and change their prefix.

I know i can change the prefix like so:

  if (prefix === 'fas') {

      icon.attr('data-prefix', 'far');
      icon.css({ color: "#d6d6d6" });
  } else {

      icon.attr('data-prefix', 'fas');
      icon.css({ color: "#3fcf8e" });
  }

I just need to know how to get all of the icons so i can just loop through them and change their prefix.


Solution

  • As far as I understand…
    You can always do it using your code, you just need to replace fas to far:

    var icons = $(".icon");
    icons.removeClass("fas");
    icons.addClass("far");
    
    // Note that this could be simplified to:
    // icons.toggleClass('far fas');
    <script defer src="https://use.fontawesome.com/releases/v5.2.0/js/all.js" integrity="sha384-4oV5EgaV02iISL2ban6c/RmotsABqE4yZxZLcYMAdG7FAPsyHYAPpywE9PJo+Khy" crossorigin="anonymous"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    fas: <i class="fas fa-circle"></i>  
    far: <i class="far fa-circle"></i>
    <br><br>
    <i class="icon fas fa-circle"></i>
    <i class="icon fas fa-circle"></i>
    <i class="icon fas fa-circle"></i>

    Hope it helps.