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.
node.firstChild;
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>
Tesla Spacex Solarcity Tesla
node.lastChild;
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>
Tesla Spacex Solarcity Solarcity