父节点查找

父节点查找:

  • parentNode 属性
  • 返回最近一级的父节点

子元素.parentNode

案例:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="father">
    <div class="son"></div>
</div>
<script>
    let son = document.querySelector(".son");
    son.parentNode.style.display = 'none';
</script>
</body>
</html>

通过`son.parentNone.就可以省去再去获取父元素的步骤,而是可以直接对父元素进行操作

子节点查找

目标:能够具备根据节点关系查找目标节点的能力

子节点查找

  • childNodes:获得所有子节点,包括文本节点(空格,换行),注释
  • children 仅获得所有元素节点,返回的还是一个伪数组

父元素.children

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<button>点击按钮变色</button>
<div class="father">
    <ul>
    <li class="son">Children</li>
    <li class="son">Children</li>
    <li class="son">Children</li>
    <li class="son">Children</li>
    <li class="son">Children</li>
    <li class="son">Children</li>
    </ul>
</div>
<script>
    let dad = document.querySelector("ul");
    let btn = document.querySelector("button");
    console.log(dad.children);
    for (let i = 0; i < dad.children.length; i++) {
        btn.addEventListener('click',function () {
            dad.children[i].style.color = 'red';
        })
    }
</script>
</body>
</html>

子集和兄弟

nextElementSibling 第二个元素的下一个元素
nextElementSibling 第二个元素的上一个元素
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div class="father">
    <button class="btn">clcik me</button>
    <ul>
        <li>第1行</li>
        <li class="main">第2行</li>
        <li>第3行</li>
    </ul>
</div>
<script>
    let btn = document.querySelector(".btn");
    let two = document.querySelector(".main");
    btn.addEventListener('click',function (){
        two.nextElementSibling.style.color = "red";
        two.previousElementSibling.style.color = "green";
    })

</script>
</body>
</html>

点击按钮后图如下,第二个的下一个元素会变红

image-20220714190934427