Loading Please Wait...
HTML DOM collection is a list of HTML elements.
The getElementsByTagName() method returns an HTMLCollection object.
An HTMLCollection object is an array-like list (collection) of HTML elements.
The following code selects all <p> elements in a document.
const myCollection = document.getElementsByTagName("p");
The elements in the collection can be accessed by an index number. The index starts at 0.
To access the second <p> element you can write
myCollection[1];
The length property defines the number of elements in an HTMLCollection.
myCollection.length;
The length property is useful when you want to loop through the elements in a collection
<html>
<body>
<h1>DOM HTML Collection</h1>
<p>Hello world 1!</p>
<p>Hello world 2!</p>
<p>Hello world 3!</p>
<button onclick="myFunction()">Click To Change Paragraph Color</button>
<script>
function myFunction() {
const myCollection = document.getElementsByTagName("p");
const colors = ['red', 'blue', 'green'];
for (let i = 0; i < myCollection.length; i++) {
myCollection[i].style.color = colors[i];
}
}
</script>
</body>
</html>
How you feel about this blog:
Share this blog on:
If you find any error in the turtorials, or want to share your suggestion/feedback, feel free to send us email at: info@lynxsia.com
Contact UsWe are concern with various development process like website design & development, E-commerce development, Software development, Application development, SMS & Bulk SMS Provider, PWA Development, and many more..
Copyright ©
, Lynxsia IT Solutions, All rights reserved