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:
document.querySelectorAll('*');
Practical example
In this example, we create a reusable function that uses querySelectorAll() method to get the collection of all HTML elements on the web page.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<h1>Header</h1>
<div>Div</div>
<script>
function findElements() {
return document.querySelectorAll('*'); // finds all elements
}
// Usage example:
window.addEventListener('load', function() {
var elements = findElements();
for (var i = 0; i < elements.length; ++i) {
console.log(elements[i]); // print element
}
});
</script>
<p>Paragraph</p>
<span>Span</span>
</body>
</html>
Note:
The
findElements()function needs to be executed after windowloadevent or at the end of the script to make sure that all elements are loaded before the function execution.