Categories
JavaScript Answers

How to change website favicon dynamically with JavaScript?

Spread the love

Sometimes, we want to change website favicon dynamically with JavaScript.

In this article, we’ll look at how to change website favicon dynamically with JavaScript.

How to change website favicon dynamically with JavaScript?

To change website favicon dynamically with JavaScript, we create a link element.

For instance, we write

const link = document.querySelector("link[rel~='icon']");
if (!link) {
  link = document.createElement("link");
  link.rel = "icon";
  document.head.appendChild(link);
}
link.href = "https://example.com/favicon.ico";

to select the link element with querySelector.

If it doesn’t exist, we create it with createElement.

And then we set its href property to the favicon’s URL.

Conclusion

To change website favicon dynamically with JavaScript, we create a link element.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *