Get the HTML content of the first child node of an <ul> element:
var x = document.getElementById("myList").firstChild.innerHTML;
Click the button to get the HTML content of the list's first child node.
Whitespace inside elements is considered as text, and text is considered as nodes.
If you add whitespace before the first LI element, the result will be "undefined".
<!DOCTYPE html> <html> <body> <p>Example list:</p> <ul id="myList"> <li>CSS</li> <li>HTML</li> </ul>//from w ww. j a va2 s . co m <button onclick="myFunction()">Test</button> <p id="demo"></p> <script> function myFunction() { var list = document.getElementById("myList").firstChild.innerHTML; document.getElementById("demo").innerHTML = list; } </script> </body> </html>
The firstChild property returns the first child node of the specified node, as a Node object.
The firstChild returns the first child node as an element node, a text node or a comment node.
The firstElementChild returns the first child node as an element node, not including text and comment nodes.
Whitespace inside elements is considered as text, and text is considered as nodes.
This property is read-only.
We can use the element.childNodes property to return any child node of a specified node.
childNodes[0] will produce the same result as firstChild.
To return the last child node of a specified node, use the lastChild property.