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 the 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
- <div id=”elementid”>
- <!—Comment Section
- Sample Snippet
- <div>
- <h1>Testing child elements in javascript</h1>
- <ul>
- <li>children</li>
- <li>childNodes</li>
- </ul>
- </div>
- </div>
childNodes Property
This property returns all child elements including the selected element, comments and text.
Return value: NodeList object
Syntax
- 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
- 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.