Javascript DOM HTML Node hasChildNodes Method

Introduction

Find out if an <ul> element has any child nodes:

Click the button to see if the ul element has any child nodes.

View in separate window

<!DOCTYPE html>
<html>
<body>

<ul id="myList">
  <li>CSS</li>
  <li>HTML</li>
</ul>//  w w  w.  j  av a2s .  c om

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

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

</body>
</html>

The hasChildNodes() method returns true if the specified node has any child nodes, otherwise false.

Whitespace inside a node is considered as text nodes, so if you leave any white space or line feeds inside an element, that element still has child nodes.

hasChildNodes();



PreviousNext

Related