Removing dynamically created elements with vanilla JavaScript by clicking on them

时间:2015-04-29 00:34:20

标签: javascript dom

I wrote the code below to dynamically add li elements to a ul element. I want the user to be able to click on any one of them and have that li item removed. I know how to do this with JQuery but I want to know how to do it with vanilla JavaScript.I understand that removeChild() is the only method at my dispose to do this but I am a bit confused as to how to use it to accomplish the task at hand.

Thank you.

http://jsfiddle.net/3wk0866o/


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) 

3 个答案:

答案 0 :(得分:1)

试试这个:

http://jsfiddle.net/3wk0866o/1/

我刚刚添加了这个监听器功能:

function removeItem(e) {
    var target = e.target;
    if(target.tagName !== 'LI') return;
    target.parentNode.removeChild(target);
}
list.addEventListener('click', removeItem);

它将一个事件监听器添加到&#34;列表&#34; UL元素,并侦听其中的点击次数。 e.target是点击的元素,如果点击的元素不是LI元素,则函数只是returns。如果是,则删除该元素及其所有子元素。

如果您想知道删除元素的最后一位是如何工作的:

target.parentNode找到点击的LI元素(UL)的父元素,然后您只需在该节点上调用removeChild,因为LIUL的子元素。您也可以直接在元素上使用remove方法,但尚未得到很好的支持。

请注意,如果LI元素包含子级,则可能会遇到问题。在这种情况下,目标可能会显示为LI个孩子中的一个,而不是LI。要解决此问题,您可以使用遍历DOM的循环,直到它到达UL元素,或直到找到要删除的LI元素:

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);

如果您的LI元素只包含其中的文字,那么第一个解决方案就足够了。

祝你好运。

答案 1 :(得分:0)

您可以使用parent.removeChild(child)删除该项目,但您可能在查找子项时遇到问题,因为该项目已动态添加。

2建议:

  1. 在将列表中的项目添加到列表中时添加该项目,然后从列表中获取它们,而不是在页面上找到它们。
  2. use。用于附加click事件的函数,然后在事件中使用它来抓取它们。

答案 2 :(得分:0)

您可以直接向新子项添加onclick事件侦听器。

function getInput(event){
    event.preventDefault();     
    var inputValue = document.getElementById("input-field").value  

    console.log(inputValue)
    form.reset();              // _______________Reset method 

    // Create new element.
    var new_li = document.createElement('li');
    new_li.innerHTML = inputValue;
    // When it is clicked, remove it.
    new_li.onclick = function() {
        this.remove();
    };

    // Append element as child to list.
    document.getElementById("list").appendChild(new_li);
}

JSFiddle