How to Find All Links On a Web Page With JavaScript

How to get all links from a page with JavaScript’s querySelectorAll, a for loop, and getAttribute

This code will grab all the links / urls from any website, and print out the link href to your console.

var links = document.querySelectorAll('a');

for (var i = 0; i < links.length; i++) {
    var link = links[i].getAttribute('href');

Tip: if you only want to grab e.g. links from an article container element (and not the entire web page) then you should make your selector method more specific. E.g. if the article you want to grab links from has a class of .article:

var articleLinks = document.querySelectorAll('.article a');

That code is more specific. It will grab only links from anchor elements a inside a parent element with the class .article.

Subscribe to Newsletter