代码:
document.querySelectorAll('a').forEach(item => {
console.log(item.nextSibling?.tagName);
})
/*
<span>1</span>
text node
<span>2</span>
<script>
document.querySelector('span').nextSibling; // #text
document.querySelector('span').nextSibling.nextSibling; // <span>2<span>
</script>
*/
我在这里没有使用
nextElementSibling
,因为我也想迭代文本节点
您的问题下的评论正确地指出,
ChildNode
可以是HTML元素之外的其他内容,因此这就是为什么像tagName
这样的属性默认情况下不起作用。
评论建议转换为 HTMLElement,但最好使用
instanceof
:
document.querySelectorAll('a').forEach(item => {
if (item.nextSibling instanceof HTMLElement) {
console.log(item.nextSibling?.tagName);
}
})
这是类型安全的,如果您愿意,它可以让您使用文本节点。
这是另一种方法,尽管我认为它不太干净:
document.querySelectorAll('a').forEach(item => {
const nextSibling = item.nextSibling;
if (nextSibling && "tagName" in nextSibling) {
console.log(nextSibling.tagName);
}
})
如果你想过滤掉除元素之外的所有内容,你可以使用类型保护:
function isHTMLElement(node: Node): node is HTMLElement {
return node instanceof HTMLElement;
}
Array.from(document.querySelectorAll('a')).filter(isHTMLElement).forEach(item => console.log(item.tagName))