使用 javascript 将类添加到第一个孩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12361616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add class to first child using javascript
提问by cmplieger
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.
它应该返回 nav 元素的第一个子元素,<a>
它不会发生。
Thanks for your help!
谢谢你的帮助!
采纳答案by Jo?o Silva
That's because you have text nodesbetween nav
and a
. You can filter them by nodeType
:
那是因为您在和之间有文本节点。您可以通过以下方式过滤它们:nav
a
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 somebrowsers may interpret the space between <nav>
and <a>
as an extratext node. Thus, firstChild
will no longer work since it'll return the text node instead.
为什么会发生这种情况?由于一些浏览器可以解释之间的空间<nav>
,并<a>
作为额外的文本节点。因此,firstChild
将不再工作,因为它将返回文本节点。
If you had the following markup, it'd work:
如果您有以下标记,它会起作用:
<nav><a>afsa</a></nav>
回答by RobG
The statement:
该声明:
document.getElementsByTagName('nav')[0].firstChild.className = "current"
is somewhat fragile as any change in the assumed document structure breaks your code. So more robust do do something like:
有点脆弱,因为假定的文档结构中的任何更改都会破坏您的代码。所以更健壮的做这样的事情:
var links,
navs = document.getElementsByTagName('nav');
if (navs) links = nav[0].getElementsByTagName('a');
if (links) links[0].className = links[0].className + ' ' + 'current';
You should also have robust addClassName and removeClassName functions.
您还应该拥有强大的 addClassName 和 removeClassName 函数。
回答by firestream
Jquery can make this very easy:
Jquery 可以让这一切变得非常简单:
$("#nav:first-child").addClass("current");