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

Popular posts from this blog

html - Outlook 2010 Anchor (url/address/link) -

javascript - Why does running this loop 9 times take 100x longer than running it 8 times? -

Getting gateway time-out Rails app with Nginx + Puma running on Digital Ocean -