JS HTML DOM element对象:previousSbling,nextSibing,parentNode:删除前一行,删除当前行,删除后一行

本文提供了一个使用纯JavaScript操作HTML列表元素的示例代码。通过简单的按钮点击即可实现删除列表中指定位置的项,包括删除前一项、当前项及后一项的功能。此代码适用于初学者了解DOM操作的基本方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
        <script type="text/javascript">
            window.onload=function(){
                var lis=document.getElementsByTagName("li");
                for (var i=0;i<lis.length;i++) {
                    var inputs=lis[i].getElementsByTagName("input");
                    inputs[0].onclick=function(){
                        var thisli=this.parentNode;
                        thisli.parentNode.removeChild(thisli.previousSibling);
                        thisli.parentNode.removeChild(thisli.previousSibling);
                    }
                    inputs[1].onclick=function(){
                        var thisli=this.parentNode;
                        thisli.parentNode.removeChild(thisli);
                    }
                    inputs[2].onclick=function(){
                        var thisli=this.parentNode;
                        thisli.parentNode.removeChild(thisli.nextSibling);  
                        thisli.parentNode.removeChild(thisli.nextSibling);  
                    }
                }
            }
        </script>
    </head>
    <body>
        <div>
            <ul>
                <li>11111111111<input type="button" value="删除前一行"/><input type="button" value="删除当前行"/><input type="button" value="删除后一行"/></li>
                <li>22222222222<input type="button" value="删除前一行"/><input type="button" value="删除当前行"/><input type="button" value="删除后一行"/></li>
                <li>33333333333<input type="button" value="删除前一行"/><input type="button" value="删除当前行"/><input type="button" value="删除后一行"/></li>
                <li>44444444444<input type="button" value="删除前一行"/><input type="button" value="删除当前行"/><input type="button" value="删除后一行"/></li>
                <li>55555555555<input type="button" value="删除前一行"/><input type="button" value="删除当前行"/><input type="button" value="删除后一行"/></li>
                <li>66666666666<input type="button" value="删除前一行"/><input type="button" value="删除当前行"/><input type="button" value="删除后一行"/></li>
                <li>77777777777<input type="button" value="删除前一行"/><input type="button" value="删除当前行"/><input type="button" value="删除后一行"/></li>
                <li>88888888888<input type="button" value="删除前一行"/><input type="button" value="删除当前行"/><input type="button" value="删除后一行"/></li>
            </ul>
        </div>
    </body>
</html>

验证截图

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值