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.