【发布时间】:2021-11-17 18:27:37
【问题描述】:
编辑:document.querySelectorAll 解决方案有效,并且更易于阅读和理解。我自己的解决方案(在下面的答案中)也有效,并且速度稍快。 getElementsByClassName + getElementsByClassName 解决方案是最快的,因此我将其标记为已接受的解决方案。
原始帖子:我需要找到具有特定类的任何元素的子元素,例如,
<li class="myclass"><a>This is the link I need to find</a></li>
这样我就可以设置和删除锚点的一些属性。
我可以使用 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');
};
如何遍历返回的元素并获取其中的标签?
【问题讨论】:
-
不要使用
getElementsBy*方法,document.querySelectorAll('.myClass a')可以解决问题。
标签: javascript dom getelementsbyclassname getelementsbytagname selectors-api