EN
JavaScript - find all links on web page
0
points
In this article, we would like to show you how to find all links on web page using JavaScript.
Quick solution:
var links = document.links;
or:
document.querySelectorAll('a[href]');
Practical examples
1. Using document.links
property
In this example, we use document.links
property that contains a collection of all <area>
elements and <a>
elements in a document.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<a href="https://dirask.com/posts" target="_blank">Link 1</a>
<script>
var links = document.links; // contains all links
// Usage example:
window.addEventListener('load', function() {
console.log([...links]);
});
</script>
<a href="https://dirask.com/snippets" target="_blank">Link 2</a>
</body>
</html>
2. Using querySelectorAll()
method
In this example, we use querySelectorAll()
method to get the collection of all links (a
elements containing href
attribute) on the web page.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<a href="https://dirask.com/posts" target="_blank">Link 1</a>
<script>
function findLinks() {
return document.querySelectorAll('a[href]'); // finds all links
}
// Usage example:
window.addEventListener('load', function() {
console.log([...findLinks()]);
});
</script>
<a href="https://dirask.com/snippets" target="_blank">Link 2</a>
</body>
</html>
Note:
The
findLinks()
function needs to be executed after windowload
event or at the end of the script to make sure that all items are loaded before the function execution.