-1

I try to add delete all to my to do app. I have something like this:

function removeAll(){
        var ol = document.getElementsByTagName('ol');
        if(ol.lenght > 0){
            ol.remove();
        }
    }
document.getElementById('delete-all').addEventListener('click', removeAll);

<input type="text" id="text-field">
<input type="button" id="add-task" value="dodaj zadanie!">
<input type="button" id="delete-all" value="usuń wszystko">

<div id="to-do-list-container">
    <ul id="task-list">
        <ol>damian</ol>
    </ul>
</div>

And it show's no errors... I check if elements with tags ol exist, then try to remove ALL elements with ol tags. I tried with ol.parrentNode.remove(); and same effect...

Damian
  • 31
  • 1
  • 7
  • 2
    `lenght` ?? is that a typo? – Suresh Atta Jan 30 '18 at 11:30
  • 1
    Aside from the typo, `
      ` is not a valid child of `
      `
    – Turnip Jan 30 '18 at 11:33
  • Oh... but now it's shows: Uncaught TypeError: ol.remove is not a function at HTMLInputElement.removeAll – Damian Jan 30 '18 at 11:33
  • I changed it for li (forgot to change it before...) - it's not vanilla js? – Damian Jan 30 '18 at 11:35
  • `ol` is a _node list_, it makes no sense to try and “remove” _that_. You need to loop over the elements contained in that node list, and then remove them individually. (And while doing so, you need to keep in mind that node lists are “live”.) – CBroe Jan 30 '18 at 11:36
  • Probably a better dupe for this scenario: https://stackoverflow.com/questions/4777077/removing-elements-by-class-name – Turnip Jan 30 '18 at 11:38

1 Answers1

1

Try the following with while loop:

function removeAll(){
  var list = document.getElementById("task-list");
  while(list.firstChild){
    list.removeChild(list.firstChild);
  }
}
document.getElementById('delete-all').addEventListener('click', removeAll);
<input type="text" id="text-field"/>
<input type="button" id="add-task" value="dodaj zadanie!"/>
<input type="button" id="delete-all" value="usuń wszystko"/>

<div id="to-do-list-container">
    <ul id="task-list">
        <ol>damian</ol>
        <ol>damian2</ol>
        <ol>damian3</ol>
    </ul>
</div>
Mamun
  • 66,969
  • 9
  • 47
  • 59