Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  139] [ 6]  / answers: 1 / hits: 30072  / 12 Years ago, tue, september 11, 2012, 12:00:00

is there any reason this chain does not work? It does not add the class:



document.getElementsByTagName('nav')[0].firstChild.className = current


It should return the first child of the nav element which is an <a> which does not happen.



Thanks for your help!


More From » javascript

 Answers
22

That's because you have text nodes between nav and a. You can filter them by nodeType:



var childNodes = document.getElementsByTagName('nav')[0].childNodes;
for (var i = 0; i < childNodes.length; i++) {
if (childNodes[i].nodeType !== 3) { // nodeType 3 is a text node
childNodes[i].className = current; // <a>
break;
}
}


It may seem strange but, for example, if you have the following markup:



<nav>
<a>afsa</a>
</nav>


Here's a DEMO.



Why does this happen? Because some browsers may interpret the space between <nav> and <a> as an extra text node. Thus, firstChild will no longer work since it'll return the text node instead.



If you had the following markup, it'd work:



<nav><a>afsa</a></nav>

[#83144] Sunday, September 9, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
freddiem

Total Points: 456
Total Questions: 116
Total Answers: 101

Location: Dominica
Member since Mon, Jan 4, 2021
3 Years ago
;