Search code examples
javascripthtmlwhile-loopremovechild

Please explain how this javaScript code removes all nodes


HTML

<ul id="myList">
   <li>Item 1</li>
   <li>Item 2</li>
   <li>Item 3</li>
   <li>Item 4</li>
</ul>

I can't seem to understand how this while statement deletes all the nodes in the above list. Can someone please explain?

JavaScript

while(myList.firstChild) {
    myList.removeChild(myList.firstChild)
};

Solution

  • Read while

    enter image description here

    HTML

    <ul id="myList">
       <li>Item 1</li>
       <li>Item 2</li>
       <li>Item 3</li>
       <li>Item 4</li>
    </ul>
    

    js code

    while(myList.firstChild) // loop will run while myList has a firstChild
        {myList.removeChild(myList.firstChild)
    };
    

    Run time

    1st time while loop run firstChild is <li>Item 1</li> --> code runs and remove it.
    

    Now HTML

    <ul id="myList">
       <li>Item 2</li>
       <li>Item 3</li>
       <li>Item 4</li>
    </ul>
    

    Run

    2nd time while loop run firstChild is <li>Item 2</li> --> code runs and remove it.
    

    Now HTML

    <ul id="myList">
       <li>Item 3</li>
       <li>Item 4</li>
    </ul>
    

    Run

    3rd time while loop run firstChild is <li>Item 3</li> --> code runs and remove it.
    

    Now HTML

    <ul id="myList">
       <li>Item 4</li>
    </ul>
    

    Run

    4th time while loop run firstChild is <li>Item 4</li> --> code runs and remove it.
    

    Now HTML

    <ul id="myList">
    </ul>
    

    Run

    js code will not run as there is no first child in myList. While loop condition fails.