Search code examples
javascriptremovechild

why a click event in javascript is removing a list item on second clik only


trying to remove a list item with a button click event but list is only deleted after the second click.

    <section class="score-panel">

    <ul id="lives">
        <li>life11</li>
        <li>life2</li>
        <li>life3</li>
    </ul>
    <button onclick="lostLives()">Remove list item</button>
    </section>

and the javascript function looks like

let lostLives = function() {
    let lives = document.getElementById('lives');
    lives.removeChild(lives.lastChild);
};

Solution

  • In order to demonstrate why there is a deletion on every second key press, change your script to this:

    let lives = document.getElementById('lives');
    console.log(lives);
    let lostLives = function() {
        lives.removeChild(lives.firstElementChild);
    };
    

    If you view your page in a browser and open up the console, you then can view the child nodes as follows:

    enter image description here

    You will notice that there are 7 nodes, not the expected 3 because the text and the element nodes are children of ul#lives. Starting at the bottom, there is a text node first so this will be deleted when the button is pressed, followed by the li element, then text etc. which is exactly what you see.

    As a further example, if you change your html to be as follows:

    <section class="score-panel">
        <ul id="lives"><li>life11</li><li>life2</li><li>life3</li></ul>
        <button onclick="lostLives()">Remove list item</button>
    </section>
    

    Then you will find that there are only 3 child nodes and your function will work as you expected it to work.

    I hope this helps.