dom - Removing dynamically created elements with vanilla JavaScript by clicking on them -
i wrote code below dynamically add li elements ul element. want user able click on 1 of them , have li item removed. know how jquery want know how vanilla javascript.i understand removechild() method @ dispose bit confused how use accomplish task @ hand.
thank you.
html
<form id="input-form"> <input id="input-field" type = "text"/> <button>submit</button> </form> <ul id="list" > </ul> javascript
var form = document.getelementbyid("input-form"); function getinput(event){ event.preventdefault(); var inputvalue = document.getelementbyid("input-field").value form.reset(); document.getelementbyid("list").innerhtml += "<li>"+ inputvalue +"</li>"; } form.addeventlistener("submit",getinput,false)
try this:
http://jsfiddle.net/3wk0866o/1/
i added listener function:
function removeitem(e) { var target = e.target; if(target.tagname !== 'li') return; target.parentnode.removechild(target); } list.addeventlistener('click', removeitem); it adds event listener "list" ul element, , listens clicks inside of it. e.target element clicked, , if element clicked isn't li element, function returns. if is, removes element , of children.
if want know how last bit removes element works:
target.parentnode finds parent element of clicked li element (ul), , call removechild on node, since li child element of ul. can use remove method on element directly, not supported yet.
note might run problems if li element has children; in case, target might show 1 of li's children , not li. solve can use loop walks through dom until gets ul element, or until finds li element remove:
http://jsfiddle.net/3wk0866o/3/
function removeitem(e) { var target = e.target; while(target.tagname !== 'ul') { if(target.tagname === 'li') { return target.parentnode.removechild(target); } target = target.parentnode; } } list.addeventlistener('click', removeitem); if li elements have text inside of them, first solution enough.
good luck.
Comments
Post a Comment