html - Building a todo list in javascript -


i'm rather new javascript , working through javascript & jquery book. test myself trying build todo list javascript. of book i've been able build of remove list function. however, can't seem addtolist function work , don't know why. insight appreciated.

var item, list, feedback; item = document.getelementbyid("item"); list = document.getelementbyid("list"); feedback = document.getelementbyid("feedback");  function addtolist() {       console.log("i 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 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> 

here see 2 mistakes:

  • you trying item element js in way item = document.getelementbyid("item"); in html <input type="text" have no item id, js code can't found element. should modify html in such way:

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

  • you sending string appendchild method - list.appendchild('<a>newelement</a>');, should accept link dom element. can rewrite in such way:

    var linktoelement = document.createelement("a"); linktoelement.appendchild(newelement); list.appendchild(linktoelement);

look here details http://jsbin.com/dowipuqayo/edit?html,js,output. it's code these changes.


Comments