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

jdpearce profile image Jo Hanna Pearce ・1 min read

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'

Posted on by:

jdpearce profile

Jo Hanna Pearce


Non-binary Nrwl (she/her). Problem-solver and science groupie. Nx & Nx Cloud Core Team.


markdown guide