In this shot, we will learn how to find the child elements inside a parent element. HTML DOM has a property that returns the object that contains all of the child elements the node has.
childNodes
and children
are similar properties, but we will discuss children
.
The main difference between the properties is that childNodes
returns all the nodes, including comments and text nodes, whereas the children
property only returns the element nodes. The children
property does not include comments or text nodes.
We will use the children
property to find the child elements of the node. This property can be used on any node.
In line 5, we have simple paragraph tags to show text.
In line 7, we use a div
element with a unique ID to get the element. The element only has 2 children, which we will find with the children
property.
In line 12, a button on click will trigger or invoke the change()
function in JavaScript.
In line 15, we have the change()
function in the script tag.
In line 16, we use the children
property on the div
element. To apply children
, we get the element with getElementById()
and store it in a variable.
In line 18, we print all elements in the div
element.
The console has an object that has 2 children nodes of the div
element. Try this on your machine and check the result.