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

How to get first childnode within a for loop

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

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;
  }
}

改用这个(收集时headers):

title = current.children[0].textContent

Demo. In other words, you should place children instead of childNodes, as with the latter both elements and text nodes are collected. Quoting 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

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