Sometimes, we want to change the website favicon dynamically with JavaScript.
In this article, we’ll look at how to change the website favicon dynamically with JavaScript.
How to change the website favicon dynamically with JavaScript?
To change the website favicon dynamically with JavaScript, we can add a link element dynamically.
For instance, we write
let 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 get the favicon link element with document.querySelector("link[rel~='icon']")
.
If it’s null
, then we create a link element with createElement
.
We set its rel
property to 'icon'
to set the rel
attribute to icon
.
And we attach the link element as the last child of the head element with document.head.appendChild(link)
.
Then we set the href
attribute value of the link element toi the favicon URL with
link.href = "https://example.com/favicon.ico";
Conclusion
To change the website favicon dynamically with JavaScript, we can add a link element dynamically.