An HTMLCollection is a live collection of elements in the DOM. This means that if the DOM is updated when a new element is added or removed , this collection updates automatically to reflect those changes.
You can access this collection using methods like document.getElementsByClassName()
or document.getElementsByTagName()
.
In the above code, the HTMLCollection is created using document.getElementsByClassName('item')
.
Initially, there are 2 elements with the class item
, so items.length
is 2.
When the "Add Item" button is clicked, a new <div>
with the class item
is dynamically added to the DOM and the items
collection automatically updates to include the new element.
The updated length of the collection reflects the changes in the DOM without needing to re-query it.