DOM 遍历是指在 HTML 文档中导航和定位元素的过程。通过 DOM 遍历,您可以在文档中移动并查找特定的元素,以便对其进行操作或者检索信息。
寻找子元素
javascript
//DOM遍历
const h1 = document.querySelector('h1');
//寻找子元素
console.log(h1.querySelectorAll('.highlight'));
上面的代码说明可以通过DOM遍历快速的定位到子元素
● 我们也可以找到元素的所有子节点(包括元素节点、文本节点和注释节点)的 NodeList 对象
javascript
console.log(h1.childNodes);

● 我们也可以找到元素的所有子元素节点,不包括文本节点和注释节点。这将返回一个 HTMLCollection 对象,其中包含所有子元素。
javascript
console.log(h1.children);

● 当然,我们可以通过这种寻找某个元素的子元素的方式来定义style
javascript
h1.firstElementChild.style.color = 'white';
h1.lastElementChild.style.color = 'orangered';

寻找父元素
● 找到元素的父节点,无论父节点是什么类型的节点(元素节点、文本节点等)。这将返回一个 Node 对象,表示 h1 元素的父节点。
javascript
console.log(h1.parentNode);

● 找到元素的最近的父元素节点。如果 h1 的父节点是一个元素节点,则返回这个元素节点;如果 h1 没有父元素节点,则返回 null。
javascript
console.log(h1.parentElement);

● 使用 closest 方法来查找最接近的具有指定选择器的祖先元素,并为找到的元素设置背景颜色。
javascript
h1.closest('.header').style.background = 'var(--gradient-secondary)';
h1.closest('h1').style.background = 'var(--gradient-primary)';

寻找兄弟元素
● 打印出该前一个兄弟元素节点
javascript
console.log(h1.previousElementSibling);

说明向上没有兄弟元素,我们也可以往下找
javascript
console.log(h1.nextElementSibling);

● h1 元素的前一个兄弟节点和后一个兄弟节点,或者如果它们不存在则显示 null。需要注意的是,这两个属性获取的节点可能是元素节点也可能是文本节点(或者其他类型的节点)。
javascript
console.log(h1.previousSibling);
console.log(h1.nextSibling);

● 那我们怎么知道元素的所有兄弟元素呢,我们可以找父元素的所有子元素
javascript
console.log(h1.parentElement.children);

● 最后,我们来玩一下,将除h1元素的所有兄弟元素缩小一半
javascript
[...h1.parentElement.children].forEach(function (el) {
if (el !== h1) el.style.transform = 'scale(0.5)';
});
