Javascript 在javascript中选择第一个div孩子的第二个孩子
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12048273/
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
Selecting second children of first div children in javascript
提问by James Harzs
I have an html that look something like this:
我有一个看起来像这样的html:
<div id="mainDiv"> <-- I have this
<div>
<div></div>
<div></div> <-- I need to get this
</div>
<span></span>
<more stuff />
</div>
i am using:
我在用:
var mainDiv = document.getElementById('mainDiv');
because I need that div in a var, but i also need to get that second div on the first div inside mainDiv into a variable.
因为我需要 var 中的那个 div,但我还需要将 mainDiv 中第一个 div 上的第二个 div 放入一个变量中。
How could I do it in a simple cross-browser way?
我怎么能以简单的跨浏览器方式做到这一点?
回答by nnnnnn
Assuming that structure is static you can do this:
假设结构是静态的,你可以这样做:
var mainDiv = document.getElementById('mainDiv'),
childDiv = mainDiv.getElementsByTagName('div')[0],
requiredDiv = childDiv.getElementsByTagName('div')[1];
Further reading: .getElementsByTagName()
(from MDN).
进一步阅读:(.getElementsByTagName()
来自 MDN)。
回答by Chao Zhang
var mainDiv = document.getElementById('mainDiv');
var x = mainDiv.children[0].children[1];
or
或者
var mainDiv = document.getElementById('mainDiv');
var x = mainDiv.getElementsByTagName('div')[0].getElementsByTagName('div')[1];
回答by Ja?ck
回答by TeeJay
I would go simply with just one line of vanilla code.
我只会用一行普通代码。
Works for any elements, is not limited to the tag names you have in the structure. But the number of elements and the hierarchy must be preserved.
适用于任何元素,不限于结构中的标签名称。但是必须保留元素的数量和层次结构。
var requiredDiv = document.getElementById('mainDiv').firstChild.firstChild.nextSibling;
回答by Musa
var mainDiv = document.getElementById('mainDiv');
var div = maindiv.getElementsByTagName('div')[2];//third div
回答by vdegenne
You know there is querySelector
now ?
你知道querySelector
现在有吗?
console.log(
mainDiv.querySelector(':nth-child(1) > :nth-child(2)'))
<div id="mainDiv">
<div>
<div></div>
<div>come get me</div>
</div>
<!-- more stuff -->
</div>