Home > Web Front-end > JS Tutorial > How Can I Dynamically Update a Website's Favicon with JavaScript?

How Can I Dynamically Update a Website's Favicon with JavaScript?

Susan Sarandon
Release: 2024-12-06 18:02:12
Original
641 people have browsed it

How Can I Dynamically Update a Website's Favicon with JavaScript?

Dynamically Updating Website Favicon

In a web application where branding is customized based on the user, dynamically changing the page favicon to reflect the private label's logo becomes imperative. However, finding code or examples to achieve this can be challenging.

One potential solution involves storing a collection of icons in a folder and dynamically generating the reference to the appropriate favicon.ico file alongside the HTML page.

Using JavaScript

To dynamically update the favicon, you can utilize JavaScript:

var link = document.querySelector("link[rel~='icon']");
if (!link) {
    link = document.createElement('link');
    link.rel = 'icon';
    document.head.appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';
Copy after login

This code selects the element with the rel attribute set to icon using the querySelector method. If no such element exists, it creates a new element, sets the rel attribute to icon, then appends it to the document's . Finally, the href attribute is updated with the desired favicon path.

By incorporating this code into your web application, you can effortlessly update the favicon based on user-specific branding, allowing for a cohesive and personalized online experience.

The above is the detailed content of How Can I Dynamically Update a Website's Favicon with JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template