JS Tutorial
JS Version
JS Objects
JS Function
JS Classes
JS Async
JS HTML DOM
JS Browser BOM
JS Web API
JS AJAX
JS JSON
JS vs JQUERY
JS Graphics
DOM Collections
The HTMLCollection Object
The getElementsByTagName() methodis used to returns an HTMLCollection object.
An HTMLCollection object is an array-like list (collection) of HTML elements.
The below code selects all <p> elements in a document:
Example
const myCollection = document.getElementsByTagName(“p”);
The elements in the collection can be accessed by an index number.
To access the second <p> element you can write:
Example
<!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>
Output
JavaScript HTML DOM
Hello World!
Hello Norway!
HTML HTMLCollection Length
The length property specifies the number of elements in an HTMLCollection.
Example
<!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>
Output
JavaScript HTML DOM
Hello World!
Hello Norway!
The length property is useful to loop through the elements in a collection:
Example
Change the text color of all <p> elements:
<!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>