Question

I'm making a to-do list to help me understand Javascript. I've managed to create a series of <li> elements with text inside. I'd like to delete the <li> elements, when they are clicked. However, at the moment they are unresponsive.

JSFIDDLE: http://jsfiddle.net/tmyie/aYLFL/

HTML:

<input id="input" placeholder="Write here">
<button>Add</button>
<hr>
<ul></ul>

Javascript:

var doc = document, // creates a variable, changing 'document' to the variable 'doc'
    list = doc.getElementsByTagName('ul')[0],
    li = doc.getElementsByTagName('li')[0],
    input = doc.getElementById('input'),
    button = doc.getElementsByTagName('button')[0]; // creates a variable called 'button', that gets the first array of all the <button> elements



button.onclick = function () {

    var mySubmission = doc.getElementById('input').value; // Get values of the input box and call it 'mySubmission'
    var item = doc.createElement('li'); // Creates a <li> element in a variable called 'item'
    item.innerHTML = mySubmission; // Inside the created 'item', the inner HTML becomes mySubmission + the class 'remove'

    list.appendChild(item); // get <ul>, and add the variable 'item'.
    doc.getElementById('input').value = ""; // resets input after submission

};

The remove function:

li.onclick = function () {

    li.parentNode.removeChild(li);

};

Excuse the excessive comments, I'm try get a better understanding of Javascript.

Was it helpful?

Solution

You define li to be:

li = doc.getElementsByTagName('li')[0]

But there are no li elements to begin with, so doc.getElementsByTagName('li')[0] returns undefined.

You'll need to move that event handler into the other callback:

list.appendChild(item); // get <ul>, and add the variable 'item'.

item.onclick = function () {
    list.removeChild(item);
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top