Reputation: 3
So basically, I want to remove the appendChild element once it has been clicked. I tried to use this.remove(), but it does not work. I manually added some divs with h2 inside of it. When I clicked the div then, my code worked. When I clicked it, it did go away.
var div_children = document.getElementById("append-div").children;
var length = div_children.length;
for (var x = 0; x < length; x++){
div_children[x].addEventListener("click", function(){
this.remove();
});
}
function myfunction(){
var new_div = document.createElement("DIV");
new_div.innerHTML = "<h2>New div</h2>";
document.getElementById("append-div").appendChild(new_div);
}
#append-div{
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
#append-div div{
background-color: lightblue;
display: flex;
flex-direction: row;
border-radius: 45px;
border: 1px solid black;
width:fit-content;
height:fit-content;
}
#append-div div h2{
margin:20px;
}
<!DOCTYPE html>
<html>
<head>
<link = rel="stylesheet" type = "text/css" href="styles.css">
<title>Test</title>
</head>
<body>
<button class = "click-me" onclick = "myfunction()">Click Me!</button>
<div id = "append-div"></div>
</body>
</html>
Upvotes: 0
Views: 886
Reputation: 13966
Try doing this
document.getElementById("append-div").outerHTML = "";
It has support on cross browsers & IE 11+
https://developer.mozilla.org/en-US/docs/Web/API/Element/outerHTML
Upvotes: 0
Reputation: 224
The issue you were having before in the removal is that the first part of the code runs without any children and it never runs again even after you create new ones.
There's no need to loop through the children to add the event listener.
Just add it to the child right after you create the element.
function myfunction() {
var new_div = document.createElement("DIV");
new_div.innerHTML = "<h2>New div</h2>";
new_div.addEventListener("click", function() {
this.remove();
});
document.getElementById("append-div").appendChild(new_div);
}
#append-div {
display: flex;
flex-direction: row;
flex-wrap: wrap;
}
#append-div div {
background-color: lightblue;
display: flex;
flex-direction: row;
border-radius: 45px;
border: 1px solid black;
width: fit-content;
height: fit-content;
}
#append-div div h2 {
margin: 20px;
}
<button class="click-me" onclick="myfunction()">Click Me!</button>
<div id="append-div"></div>
Upvotes: 2
Reputation: 2761
you could add the listener event when is created the element, as below:
function myfunction() {
var new_div = document.createElement("DIV");
new_div.innerHTML = "<h2>New div</h2>";
new_div.onclick = function () {
this.remove()
}
document.getElementById("append-div").appendChild(new_div);
}
<button class = "click-me" onclick = "myfunction()">Click Me!</button>
<div id = "append-div"></div>
Upvotes: 0