根据层级关系执行删除操作,

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script>
        //1、定义获得当前选择器对应的元素数组
        let $ = (t) => {
            return document.querySelectorAll(t);
        };

        //3、获得element的第n层父元素
        function getParent(element, index) {
            //index=0--->false
            if (index === undefined) {
                index = 1;
            }
            //index=0,先执行判断,再--
            while (index-- && element) {
                element = element.parentNode;
            }
            //
            if (!element || element.nodeType !== 1) {
                return null;
            }
            return element;
        }

        onload = () => {
            //4、获得box的所有子节点,查看信息
            let box = $(".box")[0];
            let arrChildNode = box.childNodes;
            console.log(arrChildNode.length);
            for (let i = 0; i < arrChildNode.length; i++) {
                let e = arrChildNode[i];
                if (e.nodeType === 1) {
                    e.()=>{
                        e.style.background = "yellow";
                    };
                    console.log(e + ":[nodeName=" + e.nodeName + ",nodeType=" + e.nodeType + ",nodeValue=" + e.nodeValue + "]");
                }
            }

            //5、根据层级关系执行删除操作,必须借助要删除的父级元素
            let arr = $(".deleteP");
            for(let i = 0;i<arr.length;i++){
                arr[i].()=>{
                    let arrP=getParent(arr[i],3);
                    console.log(arrP);
                    arrP.removeChild(getParent(arr[i],2));
                };
            }
            alert(getParent($("tr")[0],2));
        };

    </script>
</head>
<body>
<div class="box">
    <p class="first_p">
        <a href="#">Hello jQuery!</a>
        <a href="javaScript:void(0)" class="deleteP">删除</a>
    </p>
</div>
<div class="box">
    <p class="first_p">
        <a href="#">Hello jQuery!</a>
        <a href="javaScript:void(0)" class="deleteP">删除</a>
    </p>
</div>
<table border="1">
    <tr>
        <td></td>
    </tr>
</table>
</body>
</html>

猜你喜欢

转载自blog.csdn.net/qq_44472722/article/details/88841830