HTMLCollection and NodeList

|
| By Webner

HTMLCollection:

HtmlCollection is a collection of HTML elements from DOM. it is access by the name,id or index number. It use getElementByClassName, getElemenrtByTagName in NodeList.

It uses three Methods:

  • HTMLCollection Item() Method
  • HTMLCollection length() Method
  • HTMLCollection namedItem() Method

Html Collection Item(): it returns specificed index value for the element in an HTMLCollection.
htmllist

Html Collection Iength(): it returns the number of elements in an HtmlCollection. It is useful for elements iteration.
NodeList 1

Html Collection namedItem(): it returns the specific element by Id or class name.
htmllist2

NodeList 3

In code has three P tags, only one p has Id from all elements. In the JavaScript code get the element by tag name and mentioned the id name “collection-ID”. Click on the button just get only that element value.

NodeList:

It is a collection of nodes extracted from the Document. Browsers return the node property by childNotes. The array will not work on it. It use querySelectorAll() method for create NodeList.

Using length() property to get the number of nodes from the HTMLCollection.

var nodelist = document.querySelector(“p”);

HTML Elements:
<p>Hello World</p>
<p id=”p2-ID”>JavaScript</p>
<p>PHP</p>

JavaScriptCode:

var nodelist = document.querySelector(“p”);
document.getElementById(‘p2-ID’).innerHTML = “Total P tag =”+nodelist.length;

NodeList and HTMLCollection : JavaScript node and HTMLCollection is refer to HTML element. Both have to use the length property to get the number of elements and that is access by index number.

NodeList can not use the Array functions like. push(),pop(),join(), valueOf()

Leave a Reply

Your email address will not be published. Required fields are marked *