如何使用JavaScript在父元素的innerHTML中插入的图标删除列表标记或任何其他HTML元素?

问题描述

To-do List

在这里,我试图删除一个任务,该任务最初是使用FontAwesome中的“垃圾桶”图标创建的列表元素。我试图弄清楚在创建新任务(列表元素)时如何添加此图标。除此之外,我还想用户单击位于特定列表元素内的图标时删除任务。 我在这里共享一个Codepen链接- https://codepen.io/tsiruot/pen/yLOVyGg

   var list = document.getElementById('task-list');
var btnInput = document.getElementById('submit-btn');

btnInput.addEventListener('click',addlist);

var inputBox = document.getElementById('todo-task');

inputBox.addEventListener('keyup',function(e){
    var keyCode = e.keyCode;
    if(keyCode === 13)
    {
        addlist();
    }
})

function addlist(){
    var newElement = document.createElement('li');
    var inputValue = document.getElementById('todo-task').value;
    if(inputValue !== null && inputValue !==undefined && inputValue !=='')
    {
    newElement.appendChild(document.createTextNode(inputValue));
    list.appendChild(newElement);
    document.getElementById('todo-task').value = '';
    }
    else{
        alert('Please Add valid input value');
    }
}

function createNewNode(){
    var newElement = document.createElement('li');
    var inputValue = document.getElementById('todo-task').value;
    if(inputValue !== null && inputValue !==undefined && inputValue !=='')
    {
    newElement.appendChild(document.createTextNode(inputValue));
    return newElement;
    }
    else{
        alert('Please Add valid input value');
    }
}

var btnUpdate = document.getElementById('btn-update');

btnUpdate.addEventListener('click',function(){
    var firstElement = list.firstElementChild;
    var updatednode = createNewNode();
    list.replaceChild(updatednode,firstElement);
    document.getElementById('todo-task').value = '';
});

var btnRemove = document.getElementById('btn-remove');

btnRemove.addEventListener('click',function(){
    var firstElement = list.firstElementChild;
    list.removeChild(firstElement);
});

解决方法

常规内容:

  • 我建议使用letconst代替var作为更好的做法:Differences let,const,var
  • 始终检查列表中的元素数以确保您不会尝试删除或替换不存在的元素,我在下面的代码中添加了此类控件。

现在,让我们来满足您的要求。经过这些简短的解释后,您将在下面找到经过测试的有效代码:

  • 要将垃圾箱图标添加到每个新元素就足以创建<i>元素,请添加正确的类并将其附加到要添加到列表中的新元素。
  • 要使垃圾箱图标删除元素,只需向其添加事件侦听器。

我还添加了一些代码,以便添加到列表中的新元素获得唯一的ID。我不知道这是否对您有用,但如果不是,您可以将其删除。
现在已经有了足够的解释,让我们看一下代码:

const list = document.getElementById('task-list');
const btnInput = document.getElementById('submit-btn');
//Variable to keep track of all the elements ever created.
let elementCounter = list.children.length;

btnInput.addEventListener('click',addlist);

const inputBox = document.getElementById('todo-task');

inputBox.addEventListener('keyup',function(e) {
    const keyCode = e.keyCode;
    if(keyCode === 13)
    {
        addlist();
    }
});

function addlist()
{
    const inputValue = document.getElementById('todo-task').value;
    if(inputValue !== null && inputValue !== undefined && inputValue !== '')
    {
        //Moved the creation of the new element here so that it's not created when not necessary.
        const newElement = document.createElement('li');
        //Element for the trash icon.
        const trashIcon = document.createElement('i');
        //Add class to the element.
        trashIcon.className = 'fas fa-trash';
        //Add even listener so that when the element is clicked newElement is removed.
        trashIcon.addEventListener('click',function() {
            list.removeChild(newElement);
        });
        //Add unique ID to the new element.
        newElement.id = 'item' + ++elementCounter;
        newElement.appendChild(document.createTextNode(inputValue));
        newElement.appendChild(trashIcon);
        list.appendChild(newElement);
        document.getElementById('todo-task').value = '';
    }
    else
    {
        alert('Please Add valid input value');
    }
}

function createNewNode()
{
    const inputValue = document.getElementById('todo-task').value;
    if(inputValue !== null && inputValue !== undefined && inputValue !== '')
    {
        //Moved the creation of the new element here so that it's not created when not necessary.
        const newElement = document.createElement('li');
        //Element for the trash icon.
        const trashIcon = document.createElement('i');
        //Add class to the element.
        trashIcon.className = 'fas fa-trash';
        //Add even listener so that when the element is clicked newElement is removed.
        trashIcon.addEventListener('click',function() {
            list.removeChild(newElement);
        });
        //Add unique ID to the new element.
        newElement.id = 'item' + ++elementCounter;
        newElement.appendChild(document.createTextNode(inputValue));
        newElement.appendChild(trashIcon);
        return newElement;
    }
    else
    {
        alert('Please Add valid input value');
        //If the new element was not created,return false.
        return false;
    }
}

const btnUpdate = document.getElementById('btn-update');

btnUpdate.addEventListener('click',function() {
    //Do the following code only if there's at least one element in the list.
    if(list.children.length > 0)
    {
        const firstElement = list.firstElementChild;
        const updatedNode = createNewNode();
        //Do the following code only if the new node was created.
        if(updatedNode != false)
        {
            list.replaceChild(updatedNode,firstElement);
            document.getElementById('todo-task').value = '';
        }
    }
    else
    {
        alert('List is empty');
    }
});

const btnRemove = document.getElementById('btn-remove');

btnRemove.addEventListener('click',function() {
    //Do the following code only if there's at least one element in the list.
    if(list.children.length > 0)
    {
        const firstElement = list.firstElementChild;
        list.removeChild(firstElement);
    }
    else
    {
        alert('List is empty');
    }
});

还在HTML文件中,我删除了列表中已经存在的元素,以便所有元素都由上述javascript代码动态创建,并且事件监听器也存在并且可以正常工作。
希望这就是您想要的,随时问任何问题。

,

Here's a Codepen with your solution.

您创建一个新的图标元素并将其添加到列表中,并根据需要添加类名和ID:

function addlist(){
var newElement = document.createElement('li');
var newIcon = document.createElement('i');

var inputValue = document.getElementById('todo-task').value;
if(inputValue !== null && inputValue !==undefined && inputValue !=='')
{
newIcon.classList.add("fas");
newIcon.classList.add("fa-trash");
newIcon.setAttribute("id","icon3");
newElement.appendChild(document.createTextNode(inputValue));
list.appendChild(newElement);
newElement.appendChild(newIcon);
newElement.setAttribute("id","item3");
delButton3 = document.getElementById('icon3');
document.getElementById('todo-task').value = '';
}
else{
    alert('Please Add valid input value');
}

}

然后创建您的节点:

function createNewNode(){
var newElement = document.createElement('li');
var newIcon = document.createElement('i');
newElement.appendChild(document.createTextNode(inputValue));

var inputValue = document.getElementById('todo-task').value;
if(inputValue !== null && inputValue !==undefined && inputValue !=='')
{
    
newElement.appendChild(document.createTextNode(inputValue));
newIcon.classList.add('fas fa-trash');
list.appendChild(newIcon);
return newElement;

}
else{
    alert('Please Add valid input value');
}
var delButton3 = document.getElementById('icon3'); 

}

当找到具有该类名称的项目时,应该应用您的删除功能,因为页面加载时该元素尚不存在:

document.addEventListener('click',function(e){
if(e.target && e.target.id== 'icon3'){
      console.log('clicked')
      var item3 = document.getElementById('item3');
      item3.parentNode.removeChild(item3);
 }

});

只需检查代码笔以进行澄清:)