如何将节点“转换”为元素?
不行。
元素是节点的子集。
如果它本来就不是一个元素,那么您不能将其转化为元素。
请考虑:
<div>Hello, <strong>World</strong></div>
"Hello, "
和加粗元素节点。"Hello, "
视为元素没有意义。
children
代替childNodes
。它只获取元素子节点。
在这种情况下,最好直接使用选择器一次性获取所需元素。除了现有的选择器外,您需要使用子组合器和属性选择器。然后您需要使用我需要获取所有具有特定属性的子元素
All
来获取多个结果。document.querySelectorAll("...my selector... > [someAttribute]"
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>
children
访问所有基于HTML的节点:document.querySelector("...my selector...").children
children
吗? - Carl Edwards