Removing items from a to do list using Javascript

前端 未结 3 875
一整个雨季
一整个雨季 2021-01-07 07:31

Attempting my first Javascript project, playing around with DOM to make a To-Do List. After adding an item, how do i get the \'Remove\' button to function and remove the ite

相关标签:
3条回答
  • 2021-01-07 07:41

    Edited the Fiddle... just try this

    FiddleLink (Should work now, button and p-tag will be removed)

    HTML

    <p id="addTask"> <b><u> Tasks </u></b> </p>
    <input type='text' id='inputTask'/>
    <input type='button' onclick='addText()' value='Add To List'/>
    

    JS

    var row = 0;
    function addText(){
        var input = document.getElementById('inputTask').value;
        if(input != "")
        {
        var node=document.createElement("p");
        var textnode=document.createTextNode(input);
        node.appendChild(textnode);
            node.setAttribute("id","contentP"+row);
        document.getElementById('addTask').appendChild(node);
    
        var removeTask = document.createElement('input');
        removeTask.setAttribute('type', 'button');
        removeTask.setAttribute("value", "Remove");
        removeTask.setAttribute("id", "removeButton");
        removeTask.setAttribute("onClick", "deleterow("+ row +");");
    
        node.appendChild(removeTask);
            row++;
        }
        else
        {
            alert("Please insert a value!");
        }
    
    }
    function deleterow(ID)
    {
        document.getElementById('contentP'+ID).remove();
    }
    

    Greetings from Vienna

    0 讨论(0)
  • 2021-01-07 08:00

    You can simply assign event:

     removeTask.addEventListener('click', function(e) {
            node.parentNode.removeChild(node);
        });
    

    http://jsfiddle.net/g79ssyqv/6/

    0 讨论(0)
  • 2021-01-07 08:08

    Use this

                  // +your code 
                 .....
                 node.appendChild(removeTask);
                    // + modify
                    removeTask.onclick = function(e){
                        var dom = this;
                        var p_dom = this.parentNode;
                        console.log(p_dom);
                        var parent_node = p_dom.parentNode;
                        parent_node.removeChild(p_dom);
                    }
    
    0 讨论(0)
提交回复
热议问题