gpt4 book ai didi

javascript - 如何在for循环中获取第一个子节点

转载 作者:行者123 更新时间:2023-11-28 06:52:16 25 4
gpt4 key购买 nike

我正在尝试创建一个脚本,该脚本获取文档的所有部分,并创建一个导航,其中包含链接的 id 和 H2 作为链接文本。我尝试了多种方法,但标题未定义。我尝试使用一个类,获取第一个子节点,并将节点列表转换为数组。

http://codepen.io/brooksroche/pen/XmpNaq?editors=101

if (document.getElementsByClassName("doc-section")) {
var sections = document.getElementsByClassName("doc-section"),
sidebar = document.getElementById('sidebarNav'),
navLinks = "";
for (var i = 0; i < sections.length; ++i) {
var current = sections[i],
anchorID = current.id,
title = current.childNodes[0].text,
navLink = '<li><a href="#' + anchorID + '">' + title + '</a></li>',
navLinks = navLinks + navLink;
}
if (sidebar) {
sidebar.innerHTML = navLinks;
}
}

最佳答案

使用它(收集 header 时):

title = current.children[0].textContent

Demo 。换句话说,您应该放置 children 而不是 childNodes,因为后者会收集元素和文本节点。引用the docs :

childNodes also includes e.g. text nodes and comments. To skip them, use ParentNode.children instead.

在这种特殊情况下,结束标记和开始标记之间的空格实际上是节元素的第一个 childNode。您可以使用 .data 属性获取其文本,但它显然没有用。

实际上,您可能会认为这是一个更安全的选择:

title = current.querySelector('.sectionTitle').textContent

...这样,当相应元素的顺序发生更改时,您仍然可以从中收集文本(当然,如果类相同)。

关于javascript - 如何在for循环中获取第一个子节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32855622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com