Javascript DOM HTML Node lastChild Property with whitespace

Introduction

In this example, we demonstrate how whitespace may interact with this property.

Get the node name of the last child node of a <div> element:

Click the button get the node name of the DIV's last child node.

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

View in separate window

<!DOCTYPE html>
<html>
<head>
<style>
div {//from   w w w. ja  v  a 2s  .  com
  border: 1px solid black;
  margin: 15px;
}
</style>
</head>
<body>
<div id="myDIV">
  <p>A P element - Second child in div</p>
  <span>A Span element - Fourth child in div</span>
</div>

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

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

</body>
</html>



PreviousNext

Related