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:
xxxxxxxxxx
1
var links = document.links;
or:
xxxxxxxxxx
1
document.querySelectorAll('a[href]');
In this example, we use document.links
property that contains a collection of all <area>
elements and <a>
elements in a document.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<a href="https://dirask.com/posts" target="_blank">Link 1</a>
5
<script>
6
7
var links = document.links; // contains all links
8
9
10
// Usage example:
11
12
window.addEventListener('load', function() {
13
console.log([links]);
14
});
15
16
</script>
17
<a href="https://dirask.com/snippets" target="_blank">Link 2</a>
18
</body>
19
</html>
In this example, we use querySelectorAll()
method to get the collection of all links (a
elements containing href
attribute) on the web page.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<a href="https://dirask.com/posts" target="_blank">Link 1</a>
5
<script>
6
7
function findLinks() {
8
return document.querySelectorAll('a[href]'); // finds all links
9
}
10
11
12
// Usage example:
13
14
window.addEventListener('load', function() {
15
console.log([findLinks()]);
16
});
17
18
</script>
19
<a href="https://dirask.com/snippets" target="_blank">Link 2</a>
20
</body>
21
</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.