Search code examples
javascriptonclickclickaddeventlistenerremovechild

removeChild with addEventListener


I'm just learning javascript. Testing stuff on the google Chrome Console I ended up with this:

<html>

<head></head>
<body>

<div id="divi">

<button id="butti">Click Me</button>

</div>
</body>
</html>

And Js:

function cBoton (){
 var getDiv = document.getElementById("divi");
  getDiv.removeChild(getDiv.lastChild);
};

var getButton = document.getElementById("butti");
getButton.addEventListener("click", cBoton);

I expect the button to be deleted after one click. ¿Why works only after the second click?

tx!


Solution

  • The .lastChild of the element in your markup is "" (try console.log(getDiv.lastChild) to clarify).

    Use this to be sure that you are deleting the desired element:

    function cBoton() {
        var getDiv = document.getElementById("divi");
        getDiv.removeChild(getButton);
    };