Search code examples
htmlfavicon

Show favicon of each website in body of html


I am trying to show the tag in html along with url. Is it possible to show the favicon of each url from internet? (instead of adding before each , i want to show the favicon automatically)

is this possible?


Solution

  • Assuming your HTML looks something like this:

    <ul>
      <li class="link"><a href="https://google.com">Google.com</a></li>
      <li class="link"><a href="https://stackoverflow.com">Stackoverflow.com</a></li>
      <li class="link"><a href="https://example.com">Example.com</a></li>
    </ul>
    

    You can add a script tag and loop over each item in the list, append the standard favicon filename (favicon.ico) to that item's url and then create an image element with that url as the source

    Example:

    <ul>
      <li class="link"><a href="https://google.com">Google.com</a></li>
      <li class="link"><a href="https://stackoverflow.com">Stackoverflow.com</a></li>
      <li class="link"><a href="https://example.com">Example.com</a></li>
    </ul>
    <script>
      for (let element of document.getElementsByClassName("link")) {
        var faviconImage = document.createElement("img");
        faviconImage.src = element.children[0].href + "/favicon.ico";
        faviconImage.classList = "faviconImage";
        element.appendChild(faviconImage)
      }
    </script>