使用javascript将课程添加到第一个孩子 [英] Add class to first child using javascript

查看:50
本文介绍了使用javascript将课程添加到第一个孩子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此链有任何原因不起作用吗?它不添加类:

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

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

它应该返回nav元素的第一个子元素,这是不会发生的< a> .

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

感谢您的帮助!

推荐答案

那是因为您有 nav 和 a 之间的"nofollow> 文本节点 .您可以通过 nodeType 进行过滤:

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>

这里是 DEMO .

Here's a DEMO.

为什么会这样?因为某些浏览器可能会将< nav> < a> 之间的空间解释为 extra 文本节点.因此, firstChild 将不再起作用,因为它将返回文本节点.

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>

这篇关于使用javascript将课程添加到第一个孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆