DEV Community

Jo Hanna Pearce
Jo Hanna Pearce

Posted on

TIL: HTMLLinkElement.href returns more than you think...

I recently came across a bit of code that was trying to change the favicon on every route change of a single page application.

i.e. Every time the URL changed from /users to /users/fred a function would run that checked the current favicon href and updated it if necessary.

It did this with a tiny bit of javascript like this:

// where `expectedHref` is something like '/favicon-shop.ico'

const link = document.querySelector('link[rel*=icon]');
if (link.href !== expectedHref) {
    link.href = expectedHref;
}

What I noticed was that it was changing the favicon with every route change. Why?

It turns out that the href property on an HTMLLinkElement always returns the full URI of the linked resource rather than just the content of the href attribute!

We should have been using getAttribute instead 🤦‍♀️

link.href; // = 'http://example.com/favicon.ico'
link.getAttribute('href'); // = '/favicon.ico'

Top comments (0)