How to Retrieve Child Elements Using JavaScript

Introduction

 
JavaScript is an Object Oriented Programming language used to interact with the browser. Using it we can access the HTML DOM structure that is generated in the browser-based on the request.
 
JavaScript provides many methods and properties to achieve browser interaction. Using those members, here I'm going to show how to retrieve the child elements of the certain element from the HTML DOM.
 
JavaScript provides the following two properties to retrieve the collection of child nodes:
  • Element.childNodes (childNodes Property)
  • Element.Children (children Property)
HTML Snippet
  1. <div id=”elementid”>    
  2. <!—Comment Section    
  3. Sample Snippet    
  4. <div>    
  5.     <h1>Testing child elements in javascript</h1>    
  6.     <ul>    
  7.         <li>children</li>    
  8.         <li>childNodes</li>    
  9.     </ul>    
  10. </div>    
  11. </div>  
childNodes Property
 
This property returns all child elements including the selected element, comments and text.
 
Return value: NodeList object
 
Syntax
  1. Childnodes = document.getElementById(“elementid”).childNodes   
Example and Output
 
 
Based on the HTML snippet, this property returns the collection length as 5.
  • To get the count use the element.childNodes.length.
  • childnodes[0] or element.firstChild returns the first node from the child collection.
  • childnodes[0].nodeName returns the first element tag name.
  • childnodes[lastindexnumber] or element.lastChild returns the last node from the collection.
Children Property
 
This property returns the collection of nodes from the element without including text and comments.
 
Return Value: HTMLCollection object
 
Syntax
  1. childelements = document.getElementById(“elementid”).children   
Example and Output
 
 
Based on the HTML snippet, this property returns the collection length as 1.
  • To get the count use the element.children.length or element.childElementCount.
  • childelements[0] or element.firstElementChild returns the first element of the specified element.
  • childelements[0].tagName returns the first child element tag name.
  • childelements[lastindexnumber] or element.lastElementChild returns the last element of the specified element.