如何在JavaScript中根据子元素ID获取其在父元素中的索引
实现获取子元素在父元素中的索引函数
给定HTML结构
<div id="helo"> <span id="hjhn">sample text</span> <span id="uhed">melaps xtet</span> <span id="kdhs">elpmas txet</span> </div>
需求
实现名为helo的函数,传入子元素选择器(如#hjhn),返回该元素在父元素中的0起始索引,示例:
helo('#hjhn'); // Output: 0 helo('#uhed'); // Output: 1 helo('#kdhs'); // Output: 2
可行解决方案
方法一:数组转换 + 索引查找
简洁直观,利用数组方法快速定位索引,同时处理元素不存在的边界情况:
function helo(selector) { const target = document.querySelector(selector); if (!target) return -1; // 元素不存在时返回-1 // 将父元素的直接子元素转为数组,再查找目标元素索引 const siblingElements = Array.from(target.parentElement.children); return siblingElements.indexOf(target); }
方法二:遍历子元素手动计数
兼容性更好,适合不支持Array.from的旧环境:
function helo(selector) { const target = document.querySelector(selector); if (!target) return -1; let index = 0; let currentElement = target.parentElement.firstElementChild; // 逐个遍历父元素的直接子元素,匹配时返回计数 while (currentElement) { if (currentElement === target) { return index; } index++; currentElement = currentElement.nextElementSibling; } return -1; // 未找到目标元素(理论上不会触发) }
方法三:利用forEach遍历子元素集合
通过遍历子元素集合记录目标索引,逻辑清晰易懂:
function helo(selector) { const target = document.querySelector(selector); if (!target) return -1; let targetIndex = -1; target.parentElement.children.forEach((element, idx) => { if (element === target) { targetIndex = idx; } }); return targetIndex; }
内容的提问来源于stack exchange,提问作者BGP100
相关产品推荐
相关产品推荐

