skip to Main Content

I am want to replace a icon (Font Awesome) with an other.
I try this :

const toolbar1 = document.querySelector("#toolbar1");
  const iconToReplace = toolbar1.querySelector(".fa fa-arrows-alt");
  iconToReplace.innerHTML = '<i class="fa-fa-compress"></i>';
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

But it didn’t work.
Is there a solution?
Thanks !

2

Answers


  1. Your selector within the .querySelector() call seems invalid, it should be:

    const iconToReplace = toolbar1.querySelector(".fa.fa-arrows-alt");
    

    Furthermore, depending on the structure of the HTML, you may have intended to replace the class name of the selected element, instead of replacing the inner content of it:

    iconToReplace.classList.remove('fa-arrows-alt');
    iconToReplace.classList.add('fa-compress');
    
    document.querySelector('button').addEventListener('click', event => {
      const toolbar1 = document.querySelector("#toolbar1");
      const iconToReplace = toolbar1.querySelector(".fa.fa-arrows-alt");
      iconToReplace.classList.remove('fa-arrows-alt');
      iconToReplace.classList.add('fa-compress');
    });
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw==" crossorigin="anonymous" referrerpolicy="no-referrer" />
    
    <div id="toolbar1"><i class="fa fa-arrows-alt"></i></div>
    <button>Run</button>

    Also, you are not actually using jQuery at all in your code – is it a requirement to use it?

    Login or Signup to reply.
  2. Update the below code with your code.

    const toolbar1 = $("#toolbar1");
    const iconToReplace = toolbar1.find(".fa.fa-arrows-alt");
    iconToReplace.html('<i class="fa fa-compress"></i>');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search