HTML | DOM firstChild Property
The DOM firstChild Property is used to return the firstchild Node of its parent node element. It is read-only property and may return an element node, a text node or a comment node.
Syntax:
node.firstChild
Return Value: It returns a string value which represent the first child of a node. If the element does not have a child node then it returns a null value.
Note: Whitespace inside the parent elements is considered as text, and text is considered as nodes.
Example-1:
html
<!DOCTYPE html> < html > < head > < style > h1 { color: green; } </ style > </ head > < body style = "margin-left:140px;" > < h1 >GeeksForGeeks</ h1 > < h2 >DOM firstChild Property </ h2 > < p >List of sorting::</ p > < ul id = "GFG" >< li >Merge Sort</ li > < li >Quick Sort</ li > < li >Selection Sort</ li > < li >Bubble Sort</ li > </ ul > < button onclick = "Geeks()" >Submit</ button > < p id = "sudo" ></ p > < script > function Geeks() { var x = document.getElementById("GFG").firstChild.innerHTML; document.getElementById("sudo").innerHTML = x; } </ script > </ body > </ html > |
Output:
Before clicking on the Button:
After clicking on the button:
Example-2: To get the node name of the first child-
html
<!DOCTYPE html> < html > < head > < style > h1 { color: green; } #GFG { font-size: 20px; } </ style > </ head > < body style = "margin-left:140px;" > < h1 >GeeksForGeeks</ h1 > < h2 >DOM firstChild Property </ h2 > < div id = "GFG" > < p >first Node</ p > < span >Second Node</ span > < p >ThirdNode</ p > </ div > < br > < button onclick = "Geeks()" >Submit</ button > < p id = "sudo" style = "font-size:25PX;" ></ p > < script > function Geeks() { var x = document.getElementById("GFG").firstChild.nodeName; document.getElementById("sudo").innerHTML = "node name of the first child node " + "of a < div > element:" + x; } </ script > </ body > </ html > |
Output:
Before clicking on the button:
After clicking on the button:
Supported Browsers: The browser supported by DOM firstChild property are listed below:
- Google Chrome 1.0
- Edge 12.0
- Internet Explorer 6.0
- Firefox 1.0
- Opera 12.1
- Safari 1.0
Please Login to comment...