How to Find All Links On a Web Page With JavaScript

Learn how to grab all links from any website and print out the links to your console.

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

The code

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

for (var i = 0; i < links.length; i++) {
  var link = links[i].getAttribute("href");
  console.log(link);
}

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.


Has this been helpful to you?

You can support my work by sharing this article with others, or perhaps buy me a cup of coffee 😊

Kofi