Computer >> Computer tutorials >  >> Programming >> Javascript

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 Find All Links On a Web Page With JavaScript

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.