Javascript DOM HTML Element lastElementChild Property

Introduction

The lastElementChild property returns the last child element of the specified element.

The following code gets the HTML content of the last child element of an <ul> element:

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

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

View in separate window

<!DOCTYPE html>
<html>
<body>

<p>Example list:</p>

<ul id="myList">
  <li>CSS</li>
  <li>HTML</li>
</ul>/* w  ww . j ava2 s.  c  o  m*/


<button onclick="myFunction()">Test</button>


<p id="demo"></p>

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

</body>
</html>

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 not including text and comment nodes.

This property is read-only.

Use the children property to return any child element of a specified element.

To return the first child element of a specified element, use the firstElementChild property.

The lastElementChild property returns a Node object representing the last child element of an element, or null if there are no child elements.




PreviousNext

Related