

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
First and last child node of a specific node in JavaScript?
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
- Related Questions & Answers
- Remove the child node of a specific element in JavaScript?
- Replace a child node with a new node in JavaScript?
- Child node count in JavaScript?
- Remove all child elements of a DOM node in JavaScript?
- Insert a node as a child before an existing child in JavaScript?
- How can I remove a child node in HTML using JavaScript?
- How to get this node’s last child in a JTree with Java?
- How can I remove all child elements of a DOM node in JavaScript?
- How to get this node’s first child in a JTree with Java?
- Node in Javascript
- Program to find number of restricted paths from first to last node in Python
- Java Program to count the child of root node in a JTree
- Finding next greater node for each node in JavaScript
- Get the last node of the LinkedList in C#
- Remove Last Node of the Linked List using C++
Advertisements