How to change favicon dynamically in javascript example
- Admin
- Oct 3, 2023
- Javascript
In this tutorial, an example covers how to change the favicon programmatically.
Sometimes, We need to change the favicon icon to a new icon dynamically.
For example, a favicon declares in an HTML header tag using a link tag.
<head>
<link
id="favicon"
rel="shortcut icon"
type="image/png"
href="assets/favicon.png"
/>
</head>
href
is a favicon location
How to change favicon using javascript dynamically?
First, get the link element using Document API.
querySelector
method selects an element with id=" favicon"
.
const faviconLink = document.querySelector("#favicon");
Similarly, You can get a link element with rel='shortcut icon'
const faviconLink = document.querySelector("link[rel='shortcut icon']");
Next, Change the href with new favicon url
faviconLink.href = "newfavicon.ico";
Here is a complete example of javascript code.
const faviconLink = document.querySelector("#favicon");
faviconLink.href = "newfavicon.ico";
How to change the favicon url using jquery?
If you are using jquery in your application, It is simple to do with the attr
function.
$("link[rel='shortcut icon']").attr("href", "newfavicon.ico");
or;
$("link['#favicon']").attr("href", "newfavicon.ico");