Question

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!

Was it helpful?

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);
};

OTHER TIPS

On the first click, the last child of divi is the text node containing the whitespace after the button, and this gets removed. On the second click, the button is the last child.

Invaluable..

Modified the source;

/* .css */

div :nth-child(even){background-color: #f2f2f2}

/*.js */

function addDiv() {
var para = document.createElement("p");
var node = document.createTextNode('textHere'); // add cell code here 
para.appendChild(node);
var element;
element = document.getElementById("div1"); // to add div id recursion
element.appendChild(para);
}

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

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

/* HTML */

<html>
<head></head>
<body>
<button onclick="addDiv()">add</button>
<button onclick="cBoton()">Click Me</button>
<frameset><legend>recursions</legend>
<div id="div1"></div>
</frameset>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top