is there any reason this chain does not work? It does not add the class:
document.getElementsByTagName(\'nav\')[0].firstChild.className = \"current\"
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"; //
break;
}
}
It may seem strange but, for example, if you have the following markup:
Here's a DEMO.
Why does this happen? Because some browsers may interpret the space between and
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: