EN
JavaScript - find all elements on web page
0 points
In this article, we would like to show you how to find all elements on web page using JavaScript.
Quick solution:
xxxxxxxxxx
1
document.querySelectorAll('*');
In this example, we create a reusable function that uses querySelectorAll()
method to get the collection of all HTML elements on the web page.
xxxxxxxxxx
1
2
<html>
3
<body>
4
<h1>Header</h1>
5
<div>Div</div>
6
<script>
7
8
function findElements() {
9
return document.querySelectorAll('*'); // finds all elements
10
}
11
12
13
// Usage example:
14
15
window.addEventListener('load', function() {
16
var elements = findElements();
17
for (var i = 0; i < elements.length; ++i) {
18
console.log(elements[i]); // print element
19
}
20
});
21
22
</script>
23
<p>Paragraph</p>
24
<span>Span</span>
25
</body>
26
</html>
Note:
The
findElements()
function needs to be executed after windowload
event or at the end of the script to make sure that all elements are loaded before the function execution.