DOM Nodelist
JavaScript HTML DOM NodeList
Section titled “JavaScript HTML DOM NodeList”NodeList 是文档节点(例如,元素、文本节点)的集合。它通常由 DOM 操作方法返回。
HTML DOM NodeList
Section titled “HTML DOM NodeList”document.querySelectorAll() 和 element.childNodes 等方法会返回 NodeList。像 document.getElementsByTagName() 这样的旧方法也会返回 NodeList(或 HTMLCollection,它们类似)。
NodeList 是一种类似数组的集合 (array-like collection),这意味着它有一个 length 属性,并且可以通过索引访问其项目(例如,nodeList[0]),但它不是真正的 JavaScript Array。因此,一些数组方法可能无法直接使用。
以下代码使用 querySelectorAll 选择文档中的所有 <p> 元素:
const paragraphs = document.querySelectorAll("p");注意:访问 NodeList 中项目的索引从 0 开始。
NodeList 的 Length 属性
Section titled “NodeList 的 Length 属性”NodeList 的 length 属性表示列表中节点的数量:
const myNodeList = document.querySelectorAll("article > p"); // Selects all <p> children of <article>document.getElementById("demo").textContent = `Found ${myNodeList.length} paragraphs.`;length 属性对于遍历 NodeList 中的节点很有用。
现代迭代方法:
Section titled “现代迭代方法:”您可以使用 for...of 循环或 forEach 方法(现代浏览器中直接可在 NodeList 上使用)来遍历 NodeList:
// Using for...of loopconst articles = document.querySelectorAll('article');for (const article of articles) { article.style.border = '1px solid blue';}
// Using forEach methodconst listItems = document.querySelectorAll('ul > li');listItems.forEach((item, index) => { item.textContent = `Item ${index + 1}`;});将 NodeList 转换为数组
Section titled “将 NodeList 转换为数组”虽然 NodeList 类似数组,但它们不具备 map()、filter() 等所有数组方法。如果需要使用这些方法,可以使用 Array.from() 或展开语法 (spread syntax) (...) 将 NodeList 转换为真正的数组:
const allDivsNodeList = document.querySelectorAll('div');
// Using Array.from()const allDivsArray1 = Array.from(allDivsNodeList);const divHeights = allDivsArray1.map(div => div.offsetHeight);
// Using spread syntaxconst allDivsArray2 = [...allDivsNodeList];const divsWithClass = allDivsArray2.filter(div => div.classList.contains('special'));关键要点:NodeList 是节点的集合,类似于数组,但并不完全相同。现代 JavaScript 提供了遍历 NodeList(例如 forEach 和 for...of)的便捷方法,并在需要时可以使用 Array.from() 或展开语法将其转换为真正的数组。 |
|---|