Get "PHP 8 in a Nuthshell" (Soon includes PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

A little DevTools snippet to check broken links on a webpage

Broken links, also known as dead links, are hyperlinks on a webpage that no longer lead to the intended destination. When a user clicks on a broken link, they typically encounter a 404 error message, indicating that the webpage cannot be found.

Broken links can negatively impact user experience and SEO (Search Engine Optimization). Users who encounter them may become frustrated and leave the site, and search engines may penalize websites with many broken links, reducing their search ranking.

So, I recently came across this handy little DevTools snippet shared by jhey that can be used to track broken links on a webpage.

$$('[href]:not([href=""])').forEach(anchor => {
    console.info({ anchor, href: anchor.href })
    fetch(anchor.href)
})

Essentially, this JavaScript code snippet selects all anchor (<a>) elements in the document that have a non-empty href attribute, logs information about each of these elements to the console, and then sends a network request to each of the URLs specified in the href attributes.

You can then check the network tab in your browser’s developer tools to see if there are any 404 errors or other issues with the links on your webpage.

As mentioned by mateus in the replies of the original post, you can make it more efficient by providing the method to the fetch function which will only check the headers and prevent downloading an unnecessary body.

fetch(anchor.href, { method: 'HEAD' })

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?