【问题标题】:getElementsByTagName from a collection集合中的 getElementsByTagName
【发布时间】: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


【解决方案1】:

可以将 OP 的代码切换为更具表现力的代码(例如基于 querySelectorAll),例如 ...

document
  .querySelectorAll('.myclass a')
  .forEach(elmNode => {
    elmNode.setAttribute('role', 'link');
    elmNode.setAttribute('aria-disabled', 'true');
    elmNode.removeAttribute('href');
    elmNode.removeAttribute('rel');
  });

【讨论】:

  • 这个解决方案有效(就像我自己发布的解决方案一样)。
【解决方案2】:

问题出在getElementsByTagName 中,它返回元素的实时 HTMLCollection,您的 matches 变量包含一个数组,而必须是一个元素才能应用到他的一些属性 href, rel...,所以他需要是一个元素而不是元素s,为了解决这个问题,只需访问第一个元素而不是全部,或者使用querySelector,如果存在则返回第一个匹配的元素。

const noLinks  = document.getElementsByClassName('myclass');
for (let noLink of noLinks) {
                     //v-- access to noLink not noLinks
  const matches = noLink.getElementsByTagName('a')[0]; //<-- or noLinks.querySelector('a')
  matches.setAttribute('role', 'link');
  matches.setAttribute('aria-disabled', 'true');
  matches.removeAttribute('href');
  matches.removeAttribute('rel');
};

【讨论】:

  • 我测试了这段代码的两个版本。他们返回错误Uncaught TypeError: noLinks.querySelector is not a function,可能是因为getElementsByClassName 也返回了一个集合。这类似于我已经遇到的错误。
  • 我复制了代码 sn-p 并没有注意到您访问的 noLinks 需要 noLink 没有(s)!
  • 更正后的代码有效。您的第二条评论中仍有错字。
【解决方案3】:

以下解决方案有效。我可能会测试其他 2 个提供的解决方案,如果它们有效,我会对其进行投票,但我发布了这个答案,以便其他人可以看到解决这个问题的不同方法。

// Modify the attributes on the <a> inside the <li> with class "nolink".
const noLinks  = document.getElementsByClassName('nolink');
Array.prototype.forEach.call(noLinks, function(noLink) {
  const matches = noLink.getElementsByTagName('a')[0];
  matches.setAttribute('role', 'link');
  matches.setAttribute('aria-disabled', 'true');
  matches.removeAttribute('href');
  matches.removeAttribute('rel');
});

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-13
  • 1970-01-01
  • 2012-07-27
  • 2011-02-20
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多