Reputation: 47
<script type="text/javascript">
function create() {
var paragraph = document.createElement("p");
var item = document.getElementById("toDo").value;
paragraph.addEventListener("click", removeChild(paragraph));
paragraph.innerHTML = item;
document.body.appendChild(paragraph);
}
</script>
<div>
<h1>To Do List</h1>
<input type="text" id="toDo" placeholder="What To Do"><br>
<button type ="button" onclick="create()">Add</button>
</div>
I was creating a To-Do List and I was having problems with removing the item. I tried setAttribute("onclick", removeChild(paragraph)) but that didn't seem to work. The error "removeChild is not defined" shows up every time. How can I fix this?
Upvotes: 0
Views: 460
Reputation: 632
I have replaced paragraph
with div
because I prefer div
over everything in HTML, but the below code will work for both
<script type="text/javascript">
function create() {
const pdiv = document.createElement("div");
const item = document.getElementById("toDo").value;
pdiv.addEventListener("click", () => {
pdiv.remove();
});
pdiv.innerHTML = item;
document.body.appendChild(pdiv);
}
</script>
<div>
<h1>To Do List</h1>
<input type="text" id="toDo" placeholder="What To Do"><br>
<button type="button" onclick="create()">Add</button>
</div>
Upvotes: 1
Reputation: 626
function create() {
var paragraph = document.createElement("p");
var item = document.getElementById("toDo").value;
paragraph.innerHTML = item;
document.body.appendChild(paragraph);
paragraph.addEventListener("click", function(){document.body.removeChild(paragraph)});
}
<h1>To Do List</h1>
<input type="text" id="toDo" placeholder="What To Do"><br>
<button type ="button" onclick="create()">Add</button>
You also have to call document.body.removeChild
instead of just removeChild
.
Upvotes: 2