Search code examples
javascriptremovechild

Delete all button in to do app


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...


Solution

  • 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>