user3799793 user3799793 - 3 months ago 16
Javascript Question

Building a todo list in javascript

I'm rather new to javascript and working through javascript & jquery book. To test myself I am trying to build a todo list javascript. With the help of the book I've been able to build of the remove from list function. However, I can't seem to get the addToList function to work and I don't know why. Insight is much appreciated.

var item, list, feedback;
item = document.getElementById("item");
list = document.getElementById("list");
feedback = document.getElementById("feedback");

function addToList() {

console.log("I am in");
var newElement = document.createElement("li");
console.log(item.value);
newItem = item.value
newElement.innerHTML = newItem;
list.appendChild('<a>newElement</a>');
// el.innerHTML = item.value;
feedback.innerHTML = "Item added.";
console.log("working");
}

function removeFromList(e) {
var target, elParent, elGrandparent;
target = e.target;
elParent = target.parentNode;
elGrandparent = target.parentNode.parentNode;
elGrandparent.removeChild(elParent);
e.preventDefault();
feedback.innerHTML = "Item removed.";
}

list.addEventListener("click", function (e) {
removeFromList(e);
}, false);

var btn = document.getElementById("add");
btn.addEventListener("click", addToList, false);














<!DOCTYPE html>
<html>
<head>
<title>Todo List</title>
</head>

<body>
<input type="text" name="item"><br />
<input type="button" name="add" value="Add" id="add">

<ul id="list">
<li><a href="#">Go to the store.</a></li>
<li><a href="#">Visit family.</a></li>
</ul>

<div id="feedback"></div>


<script type="text/javascript" src="todo.js"></script>
</body>
</html>

Answer

Here I see two mistakes:

  • You are trying to get item element from JS in this way item = document.getElementById("item"); but in your HTML <input type="text" have no item id, so the JS code just can't found the element. You should modify your HTML in such way:

    <input type="text" id="item">

  • You are sending a string to appendChild method - list.appendChild('<a>newElement</a>');, but it should accept the link to the DOM element. So you can rewrite it in such way:

    var linkToElement = document.createElement("a"); linkToElement.appendChild(newElement); list.appendChild(linkToElement);

Look here for details http://jsbin.com/dowipuqayo/edit?html,js,output. It's just your code with these changes.

Comments