[英]Confused by javascript HTML DOM traversal
So I have the following HTML: 所以我有以下HTML:
<div id="mainSectionNav" class="section-container auto" data-section="" style="">
<section class="active" style="padding-top: 50px;">
<p class="title" data-section-title="" style="left: 0px;">
<a href="#panel2">Dashboard</a>
</p>
</section>
<section>
<p class="title" data-section-title="" style="left: 97px;">
</section>
And I'm trying to write a function to return the link text "Dashboard". 我正在尝试编写一个函数来返回链接文本“Dashboard”。
function zurbGetActiveSectionTab(elementId) {
var activeSectionLinkText = '';
var sectionLayout = document.getElementById(elementId);
var sections = sectionLayout.childNodes;
for(var i=0; i < sections.length; i++) {
var section = sections[i];
console.log("section tagName " + section.tagName);
if ($(section).hasClass('active')) {
var activeSectionParagraph = section.firstChild;
// if(sections[i].type == 'level2-div')
console.log("activeSectionParagraph tagName " + activeSectionParagraph.tagName);
var activeSectionLink = activeSectionParagraph.firstChild;
console.log("activeSectionLink tagName " + activeSectionLink.tagName);
activeSectionLinkText = activeSectionLink.innerHTML;
}
}
return activeSectionLinkText;
}
But what this is outputting is: 但这输出的是:
section tagName undefined
section tagName SECTION
activeSectionParagraph tagName undefined
TypeError: activeSectionLink is null
[Break On This Error]
Which has me confused. 哪个让我困惑。
Sorry for so many questions. 很抱歉这么多问题。 The more I mess with this, the more confused I'm getting.
我越乱,我就越困惑。
childNodes also returns different types of nodes, not just elements. childNodes还返回不同类型的节点,而不仅仅是元素。
If you were to look at the length of the children you will see that it is larger than you expect. 如果您要查看孩子的长度,您会发现它比您预期的要大。 You can filter them out if you want by checking the nodeType
如果需要,可以通过检查nodeType来过滤掉它们
for(var i=0; i < sections.length; i++) {
var section = sections[i];
if (section.nodeType != 1) {
continue;
}
....
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.