EN
JavaScript - find all elements inside web page body
0
points
In this article, we would like to show you how to find all elements inside web page body using JavaScript.
Quick solution:
document.body.querySelectorAll('*');
or:
document.querySelectorAll('body > *');
Practical examples
Example 1
In this example, we create a reusable function that uses querySelectorAll()
method on body
element with *
selector to get the collection of all HTML elements inside the <body>
.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<h1>Header</h1>
<div>Div</div>
<script>
function findElements() {
return document.body.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>
Example 2
In this example, we create a reusable function that uses querySelectorAll()
method on with body > *
selector to get the collection of all HTML elements inside the <body>
.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<body>
<h1>Header</h1>
<div>Div</div>
<script>
function findElements() {
return document.querySelectorAll('body > *'); // 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 windowload
event or at the end of the script to make sure that all elements are loaded before the function execution.