如何遍历getElementsByClassName返回集合调用getElementsByTagName获取子元素
原问题
我需要查找所有带有指定类名的元素的子元素,示例结构如下:
<li class="myclass"><a>This is the link I need to find</a></li>
我的目标是对这些a标签设置和移除部分属性。我可以通过getElementsByClassName轻松获取所有符合类名的列表项,但调用getElementsByTagName时失败,原因是该方法仅支持在单个确定元素上调用,无法直接作用于元素集合,因此如下代码无法正常运行:
const noLinks = document.getElementsByClassName('myclass'); for (let noLink of noLinks) { const matches = noLinks.getElementsByTagName('a'); matches.setAttribute('role', 'link'); matches.setAttribute('aria-disabled', 'true'); matches.removeAttribute('href'); matches.removeAttribute('rel'); };
请问我要如何遍历返回的元素集合,正确获取每个元素内部的指定标签?
解决方案
共有三种可正常运行的实现方案,各自特性如下:
1. 运行速度最快(已采纳):getElementsByClassName嵌套调用
该方案核心是修正原有代码的两处错误:
- 循环内错误使用元素集合
noLinks调用getElementsByTagName,替换为当前遍历到的单个元素noLink调用 getElementsByTagName返回的是HTMLCollection集合,不能直接调用属性操作方法,需要额外遍历集合内的每个a元素
实现代码如下:
const noLinks = document.getElementsByClassName('myclass'); for (let noLink of noLinks) { const aTags = noLink.getElementsByTagName('a'); for (let aTag of aTags) { aTag.setAttribute('role', 'link'); aTag.setAttribute('aria-disabled', 'true'); aTag.removeAttribute('href'); aTag.removeAttribute('rel'); } }
2. 运行速度稍快:提问者自定义实现方案
提问者自行实现的方案同样可正常运行,性能略低于嵌套调用方案,高于querySelectorAll方案。
3. 可读性最强:querySelectorAll方案
直接通过CSS选择器匹配所有符合要求的a标签,代码简洁易读,无需多层遍历:
const aTags = document.querySelectorAll('.myclass a'); aTags.forEach(aTag => { aTag.setAttribute('role', 'link'); aTag.setAttribute('aria-disabled', 'true'); aTag.removeAttribute('href'); aTag.removeAttribute('rel'); })
编辑补充:
document.querySelectorAll解决方案可行,且可读性更强。我自己在下方回答中给出的方案也可正常运行,速度稍快。而getElementsByClassName 嵌套调用的方案速度最快,因此我将其标记为已采纳答案。
内容的提问来源于stack exchange,提问作者Chris J. Zähller
相关产品推荐
相关产品推荐

