How to create or update favicon dynamically in javascript example

In this tutorial, Learn How to change or create a favicon programmatically.

Sometimes, We need to change the favicon icon to a new icon dynamically.

For example, an HTML link tag contains contains favicon path.

<head>
  <link
    id="favicon"
    rel="shortcut icon"
    type="image/png"
    href="assets/favicon.png"
  />
</head>

href is a favicon location

Create favicon using javascript

First, Create a link element using a document.createElement() method.

    var favilink = document.createElement('link');

Once created a link Object, You can add properties using

    favilink.rel = 'shortcut icon';
    favilink.href = img/favicon.ico;

Add link object to the head

    document.head.appendChild(favilink);

Here is a complete example

    var favilink = document.createElement('link');

    favilink.rel = 'shortcut icon';
    favilink.href = 'img/favicon.ico';
    document.head.appendChild(favilink);

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 a 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.

find the link object, and change the href of an object using the attr function with the new value.

$("link[rel='shortcut icon']").attr("href", "newfavicon.ico");
or;
$("link['#favicon']").attr("href", "newfavicon.ico");