{

How to change favicon dynamically in javascript example


In this tutorial, an example covers how to change 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

Changed 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 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 an complete example javascript code.

const faviconLink = document.querySelector('#favicon');

faviconLink.href = 'newfavicon.ico';

How to change favicon url using jquery?

If you are using jquery in your application, It is simple to do

$("link[rel='shortcut icon']").attr("href", "newfavicon.ico"); or 
$("link['#favicon']").attr("href", "newfavicon.ico");
THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.