Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for What is HTMLCollection in JavaScript
Alex Anie
Alex Anie

Posted on

     

What is HTMLCollection in JavaScript

HTMLCollection is a set or group of HTML elements in anarray-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 theDOM.

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()

ThegetElemenetsByTagName() 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

<ulid="parent"><liid="one"class="children">Apple</li><liid="two"class="children">Orange</li><liid="three"class="children">Lime</li><liid="four"class="children">Banana</li></ul>
Enter fullscreen modeExit fullscreen mode
constgetItemsList=document.getElementsByTagName('li');console.log(getItemsList)
Enter fullscreen modeExit fullscreen mode

Browser Preview

Image description

ThegetElementsbyTagName() method returns allli elements in the current HTML document. The returned elements are arranged in the DOM order and have alength of4 with aPrototype ofHTMLCollection.

getElementsByClassName()

ThegetElementsByClassName() method is used to get HTML elements of the same class names.

Try the code below

constgetItemsList=document.getElementsByClassName('children');console.log(getItemsList);
Enter fullscreen modeExit fullscreen mode

Browser Preview

Image description

children

Thechildren 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

constgetItemsList=document.getElementById('parent')constchildren=getItemsList.children;console.log(children);
Enter fullscreen modeExit fullscreen mode

Browser Preview

Image description

document.forms

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

<formaction=""><inputtype="text"name="text"placeholder="say something"></form><formaction=""><inputtype="button"name="button"value="button"></form>
Enter fullscreen modeExit fullscreen mode
constgetItemsList=document.forms;console.log(getItemsList);
Enter fullscreen modeExit fullscreen mode

Browser Preview

Image description

From the browser preview, the two form tags are returned by thedocument.forms property, making it a length of2.

Property and Methods

TheHTMLCollection 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
constgetItemsList=document.getElementById('parent')constchildren=getItemsList.children;console.log(children.length);
Enter fullscreen modeExit fullscreen mode
  • item(): This method returns the specified element based on the index parsed in.
constgetItemsList=document.getElementById('parent')constchildren=getItemsList.children;console.log(children.item(2));
Enter fullscreen modeExit fullscreen mode
  • namedItem(): This method returns the specified element based on the elementId parsed in.
constgetItemsList=document.getElementById('parent')constchildren=getItemsList.children;console.log(children.namedItem('four'));
Enter fullscreen modeExit fullscreen mode

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.

constgetItemsList=document.getElementById('parent')constchildren=getItemsList.children;functionbgColor(){for(letj=0;j<children.length;j++){children[j].style.color='blue';}children[3].style.color='orange';}bgColor();
Enter fullscreen modeExit fullscreen mode

Brower Preview

Image description

From the browser output, we usedforloop to loop through each item and apply acolor ofblue while for the last item, we set acolor oforange 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.

constgetItemsList=document.getElementById('parent')constchildren=getItemsList.children;constcopy=Array.from(children);console.log(copy);copy.forEach((items)=>{items.style.color='plum';})
Enter fullscreen modeExit fullscreen mode

Browser Preview

Image description

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.

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 aboutWhat 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 atocxigin@gmail.com

Cheers

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

A Frontend Developer | Technical Writer | JavaScript Developer | React.js | Next.jsFreelancer at LambdaTest Inc.Contact: Twitter @alexanie_ | Email: ocxigin@gmail.com
  • Location
    Lagos, Nigeria
  • Work
    Freelancer
  • Joined

More fromAlex Anie

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp