MutationObserver实例中mutation.type为childList时addedNodes节点的遍历方法。

2025-09-21 17:23:21 60 分享链接

二、如何遍历这个addedNodes

addedNodes 是一个包含新增 DOM 节点的数组(通过 Array.from() 转换而来),遍历它的方式和遍历普通数组一致。常用的遍历方法有以下几种,可根据具体需求选择:

1. 使用 forEach 遍历(最简洁,适合无中断需求的场景)

forEach 是数组自带的遍历方法,会依次执行回调函数处理每个元素,无法通过 break 中断。

const addedNodes = Array.from(mutation.addedNodes);

// 遍历新增节点
addedNodes.forEach((node, index) => {
  // node 是当前遍历到的 DOM 节点
  // index 是当前节点在数组中的索引(可选)
  
  // 示例1:打印节点基本信息
  console.log(`第 ${index + 1} 个新增节点:`, node);
  
  // 示例2:只处理元素节点(过滤文本/注释节点)
  if (node.nodeType === 1) { // nodeType 为 1 表示元素节点(如 div、p 等)
    console.log('元素节点标签名:', node.tagName); // 打印标签名(如 DIV、P)
    // 可在这里添加操作,比如给节点加样式、绑定事件等
    node.classList.add('newly-added'); // 给新增元素添加类名
  }
});

2. 使用 for...of 遍历(支持中断,适合需要条件跳出的场景)

for...of 是 ES6 新增的遍历语法,语法简洁且支持 break/continue 中断遍历。

const addedNodes = Array.from(mutation.addedNodes);

for (const node of addedNodes) {
  // 示例:遇到 <div> 节点则停止遍历
  if (node.nodeType === 1 && node.tagName === 'DIV') {
    console.log('找到新增的 DIV 节点,停止遍历');
    break; // 中断遍历
  }
  
  console.log('处理新增节点:', node);
}

3. 使用传统 for 循环(适合需要索引操作的场景)

传统 for 循环通过索引访问元素,灵活性高,同样支持 break/continue

const addedNodes = Array.from(mutation.addedNodes);

for (let i = 0; i < addedNodes.length; i++) {
  const node = addedNodes[i]; // 通过索引获取节点
  console.log(`索引 ${i} 的节点:`, node);
  
  // 示例:跳过文本节点(nodeType 为 3 是文本节点)
  if (node.nodeType === 3) {
    continue; // 跳过当前循环,继续下一个
  }
  
  // 对非文本节点进行操作
  console.log('非文本节点:', node);
}

关键说明:

  • 节点类型判断addedNodes 中可能包含多种类型的节点(如元素节点、文本节点、注释节点等),可通过 node.nodeType 区分:

    • nodeType === 1:元素节点(如 <div><span>
    • nodeType === 3:文本节点(纯文本内容)
    • nodeType === 8:注释节点(<!-- 注释 -->

    实际开发中通常只关注元素节点,因此建议先过滤再处理。

  • 节点操作:遍历过程中可对节点进行任何 DOM 操作,比如修改属性(node.setAttribute())、添加子节点(node.appendChild())、绑定事件(node.addEventListener())等。

根据具体需求选择合适的遍历方式即可,forEachfor...of 是最常用的两种。

MutationObserver实例中mutation.type为childList时addedNodes节点的遍历方法。