Since you are learning JavaScript, and looking at your code and accepted answer, you should take care of the following 3 things:
A. Don't use innerHTML
for adding single DOM elements.
In your code you are doing a ....innerHTML += ...
, which means the full innerHTML
is re-marked-up and inserted every time.
Meaning, for 10th li
, you are adding 10 items. For 11th li
, you are removing the 10 and then adding 11 items, instead of 1. Its bad for DOM
performance, and doesn't make sense to add all the li
s again for every li
inserted.
innerHTML
is good for one time operation.
B. Never use inline JavaScript!
It has tons of reasons. Besides, other developers in the community hate it. And looking on a question that uses it, they would run away.
<span onclick='this.parentNode.parentNode.removeChild(this.parentNode)' >
This is Bad, Bad, Very Bad!
C. Use Event Delegation!
Look at this answer.
In short, instead of having multiple click functions for every li
, its better to have a single function on ul
. If you click an li
you are also clicking the ul
. One can check which li
was clicked in the ul
and then remove it as follows:
HTML:
<form>
<input type='text' id='input' />
<input type='button' id='add-btn' value='Add' />
</form>
<ul id="do"> </ul>
JavaScript:
var doc = document,
parentUL = document.getElementById('do'),
addBtn = document.getElementById('add-btn');
addBtn.addEventListener('click', function() {
var input = doc.getElementById('input').value,
li = doc.createElement('li');
// use innerHTML only to set the conetnt of single DOM item
li.innerHTML = input + '<span style="cursor: pointer; color: red; margin-left: 20px" > x </span>';
// append only once on every create
parentUL.appendChild(li);
});
// delegate UL's click to li, by checking target item
parentUL.addEventListener('click', function(evt) {
// check the real target
var target = evt.target,
liNode = target.parentNode;
parentUL.removeChild(liNode);
});
Note: addEventListener
is for modern browsers only. Check this answer for cross browser thingy.
Collectively all this might seem an overhead for your previous small code, but this is a good practice that will save the world and JavaScript.
Although you have accepted the answer, I have updated the fiddle with above code