如何搜索嵌套对象特定属性值并返回祖先元素?遍历HTMLCollections实现
遍历HTMLCollection查找目标元素并返回对应祖先行号
需求:编写函数,遍历给定的HTMLCollection,找到innerText包含"NO"的元素,返回其最近的<tr>祖先元素的行号(即该tr在父元素中的位置序号)。
给定的HTMLCollection示例:
HTMLCollection { 0: colgroup.Table__Colgroup, 1: thead.Table__header-group.Table__THEAD, 2: tbody.Table__TBODY}
原尝试函数的问题
你写的两个函数存在几个关键问题:
- 变量未声明(比如
prprt),会导致全局污染 closest(tr)中tr未加引号,应该是字符串选择器closest('tr')indexOf用法错误,不能直接通过元素调用indexOf来获取行号,需要先将父元素的子元素转为数组再查找索引- 递归逻辑混乱,
prop[i]没有明确的索引来源,且HTMLCollection转数组的方式有误
正确实现方案
以下是可运行的实现代码,采用深度优先遍历查找目标元素,并计算对应行号:
// 主函数:遍历HTMLCollection,找到含"NO"元素的对应tr行号 function findRowWithNO(htmlCollection) { for (const element of htmlCollection) { const target = findElementWithNO(element); if (target) { const tr = target.closest('tr'); if (tr) { // 计算行号:索引从0开始,+1转为常用的从1开始的行号 return Array.from(tr.parentElement.children).indexOf(tr) + 1; } } } return null; // 未找到时返回null } // 递归函数:深度优先查找包含"NO"的元素 function findElementWithNO(element) { // 先检查当前元素的文本内容 if (element.innerText?.includes('NO')) { return element; } // 遍历所有子元素,递归查找 const children = Array.from(element.children); for (const child of children) { const result = findElementWithNO(child); if (result) { return result; } } return null; } // 使用示例:假设yearColumns是你的HTMLCollection对象 // const targetRow = findRowWithNO(yearColumns); // console.log('目标行号:', targetRow);
关键说明
- 遍历HTMLCollection时,直接用
for...of(现代浏览器支持),或者通过Array.from(htmlCollection)转为数组后遍历 - 递归函数
findElementWithNO会逐层检查元素及其子元素,确保不会遗漏嵌套的目标节点 - 找到目标元素后,
closest('tr')会向上查找最近的tr祖先,避免匹配到无关的tr - 行号计算通过将tr的父元素子节点转为数组,再用
indexOf获取位置,加1是为了符合日常从1开始计数的习惯,不需要的话可以去掉
内容的提问来源于stack exchange,提问作者barbarbytes
相关产品推荐
相关产品推荐

