sorry for my silly questions and bad explanation
Currently I’m learning JS and I couldn’t understand what went wrong.
I'm trying to make new
list when onlick the button, and I want to delete it when onclick the X
It does work in someways, but it only works when there are more than 1 of P tags. So it's impossible to remove everything which is submitted
var list = document.querySelector("#list");
var text = document.querySelector("#write");
var btn = document.querySelector("#submit");
btn.addEventListener("click", add);
function add(){
var newP = document.createElement("p");
var newUl = document.createElement("ul");
var newLi = document.createElement("li");
var newText = document.createTextNode(text.value);
var delbtn = document.createElement("span");
delbtn.setAttribute("class", "del")
var delText = document.createTextNode("X");
var delbtns = document.querySelectorAll(".del")
list.appendChild(newP);
newP.appendChild(newUl);
newUl.appendChild(newLi);
newLi.appendChild(newText);
newP.appendChild(delbtn);
delbtn.appendChild(delText);
text.value = ""
text.focus();
for (var i = 0; i < delbtns.length; i++){
delbtns[i].addEventListener("click", function () {
if(this.parentNode.parentNode)
this.parentNode.parentNode.removeChild(this.parentNode)
});
}
}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
p{
width: 80%;
}
.del{
border: 1px solid #999;
display: flex;
flex-basis: 200;
}
</style>
</head>
<body>
<h1>hello world</h1>
<form action="">
<input type="text" id="write" />
<input type="button" id="submit"/>
</form>
<div id="list"></div>
<script src="index.js"></script>
</body>
</html>
Everytime you click the add button, you're adding listener to all buttons and not removing (causing to a button to have multiple listeners).
You can set your event hander directly in
delbtnelement.Working fiddle: https://jsfiddle.net/mrlew/g1fckz6t/3/