What is HTMLCollection in JavaScript
Tags: webdev, javascript, htmlcollection, getelementsbytagname
Published: 2023-03-23 11:03:14

HTMLCollection is a set or group of HTML elements in an *array-like* manner. HTMLCollection exists in document order, based on how it is returned. Just like an array it has a length property and methods for accessing each HTML item in its collection.

HTMLCollection is said to be live because it auto-updates when a change is made to the document in the [DOM](https://www.lambdatest.com/blog/document-object-model/).

# Accessing HTMLCollection

We can access HTMLCollection using document objects in JavaScript. These objects are said to return HTMLCollection when in use.

These include;

* getElementsByTagName()
    
* getElementsByClassName()
    
* children
    
* document.forms
    

## getElementsByTagName()

The `getElemenetsByTagName()` method is used to get HTML elements with similar tag names. This is useful when we want to work with a collection of a particular element within our JavaScript file.

*Try the code below*

```xml
 <ul id="parent">
        <li id="one" class="children">Apple</li>
        <li id="two" class="children">Orange</li>
        <li id="three" class="children">Lime</li>
        <li id="four" class="children">Banana</li>
    </ul>
```

```javascript
const getItemsList = document.getElementsByTagName('li');
console.log(getItemsList)
```

Browser Preview

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3c0174nnxzk9cl006wc5.png)

The `getElementsbyTagName()` method returns all `li` elements in the current HTML document. The returned elements are arranged in the DOM order and have a `length` of `4` with a `Prototype` of `HTMLCollection`.

## getElementsByClassName()

The `getElementsByClassName()` method is used to get HTML elements of the same class names.

*Try the code below*

```javascript
const getItemsList = document.getElementsByClassName('children');
console.log(getItemsList);
```

Browser Preview


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nzd22np4z5kv8xaj2unr.png)

## children

The `children` property is used to return an HTMLCollection. This is a read-only property that returns the direct children of a given element.

*Try the code example below*

```javascript
const getItemsList = document.getElementById('parent')
const children = getItemsList.children;

console.log(children);
```

Browser Preview

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ktql7uxe19kahml5u6z2.png)

## document.forms

The `document.forms` is a read-only property that returns an HTMLCollection list of all form elements in the document.

```xml
     <form action="">
        <input type="text" name="text" placeholder="say something">
    </form>

    <form action="">
        <input type="button" name="button" value="button">
    </form>
```

```javascript
const getItemsList = document.forms;
console.log(getItemsList);
```

Browser Preview


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/60ju41k841hfq3titct5.png)

From the browser preview, the two form tags are returned by the `document.forms` property, making it a length of `2`.

# Property and Methods

The `HTMLCollection` comes with in-built property and methods that can be used to access the modify the elements within the HTMLCollection list. these include.

* **length:** This property returns the total length of tags present in the HTMLCollection
    

```javascript
const getItemsList = document.getElementById('parent')
const children = getItemsList.children;

console.log(children.length);
```

* **item():** This method returns the specified element based on the index parsed in.
    

```javascript
const getItemsList = document.getElementById('parent')
const children = getItemsList.children;

console.log(children.item(2));
```

* **namedItem():** This method returns the specified element based on the element `Id` parsed in.
    

```javascript
const getItemsList = document.getElementById('parent')
const children = getItemsList.children;

console.log(children.namedItem('four'));
```

# Using Forloop

HTMLCollection is an array-like collection of HTML elements and as a result, it can be iterated with a forloop to loop through each item in the collection.

```javascript
const getItemsList = document.getElementById('parent')
const children = getItemsList.children;

function bgColor(){
    for(let j = 0; j < children.length; j++){
        children[j].style.color = 'blue';
    }

    children[3].style.color = 'orange';
}
bgColor();
```

Brower Preview


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1t1kvw5hfgrmea97ujy1.png)

From the browser output, we used `forloop` to loop through each item and apply a `color` of `blue` while for the last item, we set a `color` of `orange` by specifying the index of the element in the HTMLCollection.

# Converting HTMLCollection to an Array (Array.from) Method

HTMLCollection doesn't have JavaScript built-in array methods available. However, converting it to a regular array is required in other to manipulate it with the array methods.

```javascript
const getItemsList = document.getElementById('parent')
const children = getItemsList.children;

const copy = Array.from(children);
console.log(copy);

copy.forEach((items)=>{
   items.style.color = 'plum';
})
```

Browser Preview


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wtx85swzm4wzzdq0pr31.png)

From the browser preview, notice the prototype is now an array.

# Adding Items to HTMLCollection

We can add and remove items from HTMLCollection directly from our JavaScript file.

*Try the code example below.*

{% codepen https://codepen.io/ocxigin/pen/KKxGagm %}

HTMLCollection returns a live collection list items, This means when an item is added to the page, it auto-update it in the DOM. The project above display this in action.  
  
Simply add your favorite fruit to the fruit list items and click add, click remove to remove the fruit from the bottom.  
  
While you perform this action, open up your browser console. Any item you add or remove will return the total length of the array in the item list.

# Wrapping up

We learned about *What is HTMLCollection* in JavaScript and we discussed the following.

* What is HTMLCollcetion
    
* Accessing HTMLCollcetion
    
* HTMLCollection property and methods
    
* Using forloop with HTMLCollection
    
* Converting HTMLCollection to an Array (Array.from) Method
    
* Adding Items to HTMLCollection
    

Alright! We’ve come to the end of this tutorial. Thanks for taking the time to read this article to completion. Feel free to ask questions. I’ll gladly reply. You can find me on Twitter and other social media @ocxigin. or email me at ocxigin@gmail.com

*Cheers*