Javascript DOM HTML Node removeChild Method remove first child

Introduction

Find out if a list has any child nodes. If so, remove its first child node:

Click the button to see if the ul element has any child nodes. If so, remove its first child node.

The <li> elements inside <ul> are not indented.

If they were, the first child node of <ul> would be a text node.

View in separate window

<!DOCTYPE html>
<html>
<body>
<ul id="myList"><li>CSS</li><li>HTML</li><li>Java</li></ul>
<button onclick="myFunction()">Test</button>

<script>
function myFunction() {/* w  w  w. j  a  v  a 2  s  .c  o m*/
  var list = document.getElementById("myList");

  if (list.hasChildNodes()) {
    list.removeChild(list.childNodes[0]);
  }
}
</script>

</body>
</html>



PreviousNext

Related