GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

No menu could be recovered. Follow the blue links in the page.

This view

  • Original page
  • New address

GeezerVison is showing javascript.info — Clear the element

  • Tutorial
  • Browser: Document, Events, Interfaces
  • Document
  • Modifying the document
back to the lesson

Clear the element

importance: 5

Create a function clear(elem) that removes everything from the element.

<ol id="elem">
  <li>Hello</li>
  <li>World</li>
</ol>

<script>
  function clear(elem) { /* your code */ }

  clear(elem); // clears the list
</script>

First, let’s see how not to do it:

function clear(elem) {
  for (let i=0; i < elem.childNodes.length; i++) {
      elem.childNodes[i].remove();
  }
}

That won’t work, because the call to remove() shifts the collection elem.childNodes, so elements start from the index 0 every time. But i increases, and some elements will be skipped.

The for..of loop also does the same.

The right variant could be:

function clear(elem) {
  while (elem.firstChild) {
    elem.firstChild.remove();
  }
}

And also there’s a simpler way to do the same:

function clear(elem) {
  elem.innerHTML = '';
}
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.