kembali ke pelajaran
Materi ini hanya tersedia dalam bahasa berikut: English, Espa??ol, Fran??ais, Italiano, ?????????, ?????????, ??????????????, T??rk??e, ????????????????????, ????????????. Tolong, menerjemahkan ke dalam Indonesia.

Clear the element

pentingnya: 5

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

<ol id="elem">

  function clear(elem) { /* your code */ }

  clear(elem); // clears the list

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

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

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) {

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

function clear(elem) {
  elem.innerHTML = '';