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:
xxxxxxxxxx
1
document.head.querySelectorAll('*');
or:
xxxxxxxxxx
1
document.querySelectorAll('head > *');
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>
.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<title>Title of the document</title>
5
<!-- example meta tags -->
6
<meta property="og:site_name" content="Dirask.com, IT Community">
7
<meta property="og:url" content="https://dirask.com/posts/D6BelD">
8
<meta property="og:type" content="article">
9
</head>
10
<body>
11
<script>
12
13
function findElements() {
14
return document.head.querySelectorAll('*'); // finds all elements in head
15
}
16
17
18
// Usage example:
19
20
window.addEventListener('load', function() {
21
var elements = findElements();
22
for (var i = 0; i < elements.length; ++i) {
23
console.log(elements[i]); // print element
24
}
25
});
26
27
</script>
28
</body>
29
</html>
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>
.
xxxxxxxxxx
1
2
<html>
3
<head>
4
<title>Title of the document</title>
5
<!-- example meta tags -->
6
<meta property="og:site_name" content="Dirask.com, IT Community">
7
<meta property="og:url" content="https://dirask.com/posts/D6BelD">
8
<meta property="og:type" content="article">
9
</head>
10
<body>
11
<script>
12
13
function findElements() {
14
return document.querySelectorAll('head > *'); // finds all elements inside head
15
}
16
17
18
// Usage example:
19
20
window.addEventListener('load', function() {
21
var elements = findElements();
22
for (var i = 0; i < elements.length; ++i) {
23
console.log(elements[i]); // print element
24
}
25
});
26
27
</script>
28
</body>
29
</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.