Let's discuss each approach one by one.
It is an example code that will help us to understand how to fetch the child elements of a particular node:Test it Now
Now, using this example code, we will understand each approach that we have described above.
Getting First Child Element of a Node
In order to get the first child element of a node, it is required to use the firstChild property of the element.
In the described syntax, the variable firstchild will hold the value of the first child element, and the parentElement is the parent node of which we are trying to get the first child element value.
Points to be noted:
Let's see the below code example to understand how to use the firstChild property:
In the above code, we have stored the <ul> element id to the frstchild variable, and then we have fetched the first child element value and stored it frstchild variable. Finally, we have the output that child element value.
We can see in the below output:
Getting the last child element of a node
In order to get the last child element of a node, we need to use the lastChild property.
The lastChild variable will hold the value of the last child element present in the parent node.
Examine the below part of the example code:
So, in the above code, we can see that similar to the retrieval of the first child element of a node, we have used the lastElementChild method to fetch the last child. However, if there is no child element present in the parent node, the property returns null. Otherwise, it will return the last child element value if present.
We have the following output:
Point to be noted:
Getting all the child elements of a node
In order to get all the child elements of a node, use childNodes or children properties. Both these properties can be used to get all the specified children of a parent node, but the difference between both is that the childNodes property will return all the child elements with any node type, i.e., the live NodeList of all child nodes of any node type whereas the children property will return the child element nodes with only the node type.
Let's see the syntax for both properties:
The childNodes Property
The children Property
Look at the below example code section to see how to get all the child elements:
In the section of code, we are getting all the child elements of the parent node using the children property, as we can see in the below snapshot: