JavaScript HTML DOM Collections
The HTMLCollection Object
The getElementsByTagName()
function gives back an HTMLCollection
object.
An HTMLCollection
is a list of HTML elements that behaves like an array
The code below chooses all <p>
elements in a document.
Note: The counting begins from zero.
HTML HTMLCollection Length
The length
property tells us how many elements are in an HTMLCollection
.
The length
property comes in handy when you need to go through the elements in a group.
HTML Collection is different from an array!
An HTML Collection might seem similar to an array, but it's not the same.
You can go through the list and point to the items using a number, similar to how you would with an array.
But, you can't apply array methods such as valueOf(), pop(), push(), or join() to an HTMLCollection.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Hello World!</p>
<p>Hello Norway!</p>
<p id="demo"></p>
<script>
const myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = "The innerHTML of the second paragraph is: " + myCollection[1].innerHTML;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Hello World!</p>
<p>Hello Norway!</p>
<p id="demo"></p>
<script>
const myCollection = document.getElementsByTagName("p");
document.getElementById("demo").innerHTML = "This document contains " + myCollection.length + " paragraphs.";
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript HTML DOM</h2>
<p>Hello World!</p>
<p>Hello Norway!</p>
<p>Click the button to change the color of all p elements.</p>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
const myCollection = document.getElementsByTagName("p");
for (let i = 0; i < myCollection.length; i++) {
myCollection[i].style.color = "red";
}
}
</script>
</body>
</html>