Loading Please Wait...

Logo Lynxsia IT Solutions

JavaScript HTML DOM Collections

JS HTML DOM Collections

HTML DOM collection is a list of HTML elements.

The HTMLCollection Object

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];
        
      
HTML HTMLCollection Length

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:

Report Us

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 Us
Ads
Logo
Lynxsia IT Solutions

We 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..

Kotwali Road, Chhiptehri, Banda, 210001, UP, India

Copyright © 2022, Lynxsia IT Solutions, All rights reserved