如何删除< li>从列表与JavaScript [英] How to delete an <li> from list with javascript

查看:68
本文介绍了如何删除< li>从列表与JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的是使用javscript从DOM中删除用户单击的所有列表项.这是我的代码:

What im trying to do is to remove whatever list item a user clicks on from the DOM using javscript. This is my code:

// Delete shape from ul event
    shapeList.onclick = function (event) {
        var shapesArray = shapesCtrl.getShapesArray();
        var target = event.target; // Getting which <li> was clicked
        var id = target.parentNode.id; // Getting the value of the li that was clicked
        canvasCtrl.deleteShape(shapesArray, id); // Deleting the targeted element from the array 

        var li = shapeList.childNodes;

        // Above i remove the object that the corresponds with the li the user clicked on but i cant remove the actual li itself... Ive tried to use li[id].remove() but it just keeps removing the 1st li even though the id might point to the last item for example.

    };

有人可以帮我用香草js而不是jquery做到这一点吗?谢谢!:)

Can anybody please help me do this with vanilla js and not jquery. Thanks! :)

推荐答案

基于您的标记:

<ul id ="shape-list" class="list-group mt-3 mb-3"> 
<li>Link: url.com <i class="delete-icon fas fa-trash-alt"></i> </li> 
</ul>

您可以简单地使用 Node 方法

You can simply use the Node method removeChild. This is assuming that the i tag is the target in your event.

 target.parentNode.parentNode.removeChild(target.parentNode);

在代码内:

// Delete shape from ul event
shapeList.onclick = function (event) {
    var shapesArray = shapesCtrl.getShapesArray();
    var target = event.target; // Getting which <li> was clicked
    var id = target.parentNode.id; // Getting the value of the li that was clicked
    canvasCtrl.deleteShape(shapesArray, id); // Deleting the targeted element from the array 

    var li = shapeList.childNodes;

    target.parentNode.parentNode.removeChild(target.parentNode);
};

这篇关于如何删除&lt; li&gt;从列表与JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆