To get the first and last child nodes of a specific node, javascript has provided firstChild and lastChild methods respectively. let's discuss them in a nutshell.
FirstChild
syntax
node.firstChild;
Example
In the following example, there are three elements in the list node. Using the method "firstChild" the first element is found out and the result is displayed in the output.
<html> <body> <ul id = "list"><li>Tesla</li><li>Spacex</li><li>Solarcity</li></ul> <p id="first"></p> <script> var list = document.getElementById("list").firstChild.innerHTML; document.getElementById("first").innerHTML = list; </script> </body> </html>
Output
Tesla Spacex Solarcity Tesla
LastChild
syntax
node.lastChild;
Example-2
In the following example, there are three elements in the list node. Using the method "lastChild" the last element is found out and the result is displayed in the output.
<html> <body> <ul id = "list"><li>Tesla</li><li>Spacex</li><li>Solarcity</li></ul> <p id="first"></p> <script> var list = document.getElementById("list").lastChild.innerHTML; document.getElementById("first").innerHTML = list; </script> </body> </html>
Output
Tesla Spacex Solarcity Solarcity