Javascript DOM HTML Node lastChild Property

Introduction

Get the HTML content of the last child node of an <ul> element:

var x = document.getElementById("myList").lastChild.innerHTML;

Click the button to get the HTML content of the list's last child node.

Whitespace inside elements is considered as text, and text is considered as nodes.

If you add whitespace before the closing UL element, the result will be "undefined".

View in separate window

<!DOCTYPE html>
<html>
<body>

<p>Example list:</p>
<ul id="myList">
   <li>CSS</li>
   <li>HTML</li>
</ul>/*from  w  w w . j  ava2 s .  c  o  m*/

<button onclick="myFunction()">Test</button>
<p id="demo"></p>

<script>
function myFunction() {
  var list = document.getElementById("myList").lastChild.innerHTML;
  document.getElementById("demo").innerHTML = list;
}
</script>

</body>
</html>

The lastChild property returns the last child node of the specified node, as a Node object.

The lastChild returns the last child node as an element node, a text node or a comment node.

The lastElementChild returns the last child node as an element node ignoring 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.

To return the first child node of a specified node, use the firstChild property.




PreviousNext

Related