user3799793 user3799793 - 1 year ago 136
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");
newItem = item.value
newElement.innerHTML = newItem;
// el.innerHTML = item.value;
feedback.innerHTML = "Item added.";

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

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

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

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

<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>

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

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

Answer Source

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,js,output. It's just your code with these changes.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download