Basic DOM scripting with event delegation
by OmShiv
HTML
<form>
<input type='text' id='input' />
<input type='button' id='addBtn' value='Add' />
</form>
<ul id="do"> </ul>
CSS
/* I like style, hence the CSS. you can simply delete all this */
ul li {
width: 50%;
padding-left: 20px;
list-style-type: none;
border: 1px solid #888;
margin-bottom: 5px;
box-shadow: 5px 5px 10px rgba(0,0,0,0.3);
}
li span {
float: right;
display: inline-block;
background-color: #FFA479;
padding: 0 20px;
}
li span:hover {
background-color: lightpink;
}
li span:active {
box-shadow: 0 0 10px rgba(0,0,0,0.3) inset;
}
JavaScript
var doc = document,
parentUL = document.getElementById('do'),
addBtn = document.getElementById('addBtn');
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);
});