如何在JavaScript中获取所有具有特定属性的子元素

4

我有一个对象,它是从这个表达式中检索到的:

const element = document.querySelector("...my selector...");

我需要获取所有具有特定属性的子元素,我知道的获取所有子元素的唯一方法是:

const children = Array.from(element.childNodes);

但是现在,children中的每个child都不是一个元素,而是一个节点,因此,我无法对它们使用getAttribute('')

如何将Node“转换”为Element?或者有更好的方法吗?


1
你尝试过使用 children 吗? - Carl Edwards
1
那么使用CSS子选择器和querySelectorAll吗? - epascarello
1
那么你要选择的实际HTML是什么? - epascarello
@epascarello,我正在编写一个简单的机器人(爬虫)来检索一些数据。实际数据在“anchor”元素中。 - WhiZTiM
3个回答

9
您好,以下为翻译内容:

如何将节点“转换”为元素?

不行。

元素是节点的子集。

如果它本来就不是一个元素,那么您不能将其转化为元素。

请考虑:

<div>Hello, <strong>World</strong></div>

您有两个子节点,文本节点"Hello, "和加粗元素节点。
"Hello, "视为元素没有意义。
考虑使用children代替childNodes。它只获取元素子节点。

我需要获取所有具有特定属性的子元素

在这种情况下,最好直接使用选择器一次性获取所需元素。除了现有的选择器外,您需要使用子组合器和属性选择器。然后您需要使用All来获取多个结果。
document.querySelectorAll("...my selector... > [someAttribute]"

5
您说您想选择所有具有特定属性的子元素。因此,可以使用属性选择器通过querySelectorAll选择它们。

var elems = document.querySelectorAll("#theParentSelector > [theChildsAttribute]")
console.log(elems.length)
Array.from(elems).forEach( function (el) {
   console.log(el.getAttribute("theChildsAttribute"))
});
<div id="theParentSelector">
  <div theChildsAttribute="1">Foo 1</div>
  <div>Bar</div>
  <div theChildsAttribute="2">Foo 2</div>
  <div theChildsAttribute="3">Foo 3</div>
</div>


3
您可以使用children访问所有基于HTML的节点:
document.querySelector("...my selector...").children

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接