Consider this HTML and the functions below to reference its HTML elements:
<body id="body">
<div class="container">
<h2 name="h" class="header">Header 1.1</h2>
<h2 name="h" class="header">Header 1.2</h2>
</div>
</body>
| Method | Returns | Return type |
|---|---|---|
document.body |
body | Element |
document.getElementById("body") |
body | Element |
document.getElementsByClassName("container") |
[div] | HTMLCollection<Element> |
document.getElementsByClassName("header") |
[h2, h2] | HTMLCollection<Element> |
document.getElementsByTagName("h2") |
[h2, h2] | HTMLCollection<Element> |
document.getElementsByName("h") |
[h2, h2] | NodeList<Element> |
document.querySelector("h2") |
h2 | Element |
document.querySelectorAll("h2") |
[h2, h2] | static NodeList<Element> |
document.querySelectorAll("h2")[1] |
h2 | Element (at index 1) |
Create an empty file index.html and paste the code below:
<body id="body" onload="loaded()">
<div class="container">
<h2 name="h" class="header">Header 1.1</h2>
<h2 name="h" class="header">Header 1.2</h2>
</div>
</body>
<script>
function loaded() {
console.log('document.body', document.body);
console.log('document.getElementById("body")', document.getElementById("body"));
console.log('document.getElementsByClassName("container")', document.getElementsByClassName("container"));
console.log('document.getElementsByClassName("header")', document.getElementsByClassName("header"));
console.log('document.getElementsByTagName("h")', document.getElementsByTagName("h2"));
console.log('document.getElementsByName("h")', document.getElementsByName("h"));
console.log('document.querySelector("h2")', document.querySelector("h2"));
console.log('document.querySelectorAll("h2")', document.querySelectorAll("h2"));
console.log('document.querySelectorAll("h2")', document.querySelectorAll("h2")[1]);
}
</script>
A NodeList retrieved with getElementsByName is a list of Elements that keeps itself up-to-date when the DOM changes.
querySelectorAll returns a static NodeList object, meaning that changes in the DOM do not effect the collection.
In order to manipulate or filter the list of retrieved objects, the returned collection (HTMLCollection or NodeList) need to be converted to an array. The following code shows how a map function cannot be performed on a NodeList…
const headerTexts = document.querySelectorAll("h2").map(x => x.innerHTML);
and results in error:
document.querySelectorAll(...).map is not a function
HTMLCollection and NodeList are iterable so you can use the spread syntax to convert them to arrays like this:
[...document.querySelectorAll("h2")]
Getting the innerHTML of each header would look like this:
const headerTexts = [...document.querySelectorAll("h2")].map(x => x.innerHTML);
console.log(headerTexts);
Output:
["Header 1.1", "Header 1.2"]
[...document.querySelectorAll("h2")].map(x => x.innerHTML = x.innerHTML.split("").reverse().join(""));
Try it with the h2 headers on this page: