如何根据属性值删除NodeList中的节点或获取其索引?
处理NodeList并忽略指定属性节点的两种实现方法
方法1:过滤/移除AttributeName为"b"的节点
NodeList是类数组对象,无法直接删除元素,我们可以先将其转换为数组,再通过过滤得到不含目标节点的集合;如果需要从XML文档中真正移除该节点,可遍历找到目标节点后调用DOM删除方法。
// 1. 仅获取过滤后的节点集合(不修改原文档) const nodeList = document.querySelectorAll('ThisNode'); const filteredNodes = Array.from(nodeList).filter(node => node.getAttribute('AttributeName') !== 'b' ); // 2. 从XML文档中删除目标节点 Array.from(nodeList).forEach(node => { if (node.getAttribute('AttributeName') === 'b') { node.parentNode.removeChild(node); } });
方法2:通过索引排除目标节点
先遍历NodeList找到AttributeName为"b"的节点索引,之后遍历过程中跳过该索引即可。
const nodeList = document.querySelectorAll('ThisNode'); let targetIndex = -1; // 定位目标节点的索引 Array.from(nodeList).forEach((node, index) => { if (node.getAttribute('AttributeName') === 'b') { targetIndex = index; } }); // 遍历并跳过目标索引的节点执行操作 for (let i = 0; i < nodeList.length; i++) { if (i !== targetIndex) { // 这里写入你需要对节点执行的操作 console.log(nodeList[i]); } } // 或者用数组forEach方式 Array.from(nodeList).forEach((node, index) => { if (index !== targetIndex) { // 执行操作 console.log(node); } });
内容的提问来源于stack exchange,提问作者Sergei Walankov
相关产品推荐
相关产品推荐

