EN
JavaScript - find all elements inside web page head element
0
points
In this article, we would like to show you how to find all elements inside web page header using JavaScript.
Quick solution:
document.head.querySelectorAll('*');
or:
document.querySelectorAll('head > *');
Practical examples
Example 1
In this example, we create a reusable function that uses querySelectorAll()
method on head
element with *
selector to get the collection of all HTML elements inside the <head>
.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<title>Title of the document</title>
<!-- example meta tags -->
<meta property="og:site_name" content="Dirask.com, IT Community">
<meta property="og:url" content="https://dirask.com/posts/D6BelD">
<meta property="og:type" content="article">
</head>
<body>
<script>
function findElements() {
return document.head.querySelectorAll('*'); // finds all elements in head
}
// Usage example:
window.addEventListener('load', function() {
var elements = findElements();
for (var i = 0; i < elements.length; ++i) {
console.log(elements[i]); // print element
}
});
</script>
</body>
</html>
Example 2
In this example, we create a reusable function that uses querySelectorAll()
method on with head > *
selector to get the collection of all HTML elements inside the <head>
.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<title>Title of the document</title>
<!-- example meta tags -->
<meta property="og:site_name" content="Dirask.com, IT Community">
<meta property="og:url" content="https://dirask.com/posts/D6BelD">
<meta property="og:type" content="article">
</head>
<body>
<script>
function findElements() {
return document.querySelectorAll('head > *'); // finds all elements inside head
}
// Usage example:
window.addEventListener('load', function() {
var elements = findElements();
for (var i = 0; i < elements.length; ++i) {
console.log(elements[i]); // print element
}
});
</script>
</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.