javascript - How to get first childnode within a for loop -
i'm trying create script gets sections of documentation , creates navigation id link , h2 link text. i've tried several ways , title undefined. i've tried using class, getting first child node, , converting nodelist array.
http://codepen.io/brooksroche/pen/xmpnaq?editors=101
if (document.getelementsbyclassname("doc-section")) { var sections = document.getelementsbyclassname("doc-section"), sidebar = document.getelementbyid('sidebarnav'), navlinks = ""; (var = 0; < 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; } }
use instead (when collecting headers):
title = current.children[0].textcontent
demo. in other words, should place children
instead of childnodes
, latter both elements , text nodes collected. quoting the docs:
childnodes includes e.g. text nodes , comments. skip them, use
parentnode.children
instead.
in particular case, whitespace between closing tag , opening tag first childnode
of section element. able text .data
property, of no use.
actually, might consider safer alternative:
title = current.queryselector('.sectiontitle').textcontent
... when corresponding element's order changed, you'll still able collect text (if class same, of course).
Comments
Post a Comment