Javascript DOM HTML Node hasChildNodes Method check

Introduction

Remove the first child node inside an <ul> element, if the element has any child nodes.

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

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

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

If so, remove its first child node.

View in separate window

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

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

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

</body>
</html>



PreviousNext

Related