Javascript 如何在Jquery中通过索引获取子元素?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8926678/
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
How to get child element by index in Jquery?
提问by Davor Zubak
<div class="second">
<div class="selector" id="selFirst"></div>
<div class="selector" id="selSecond"></div>
<div></div>
</div>
How to get #selFirst using element index not the ID?
如何使用元素索引而不是 ID 获取#selFirst?
this:
这个:
var $selFirst = $(".second:nth-child(1)");
console.log($selFirst);
is returning :
正在返回:
jQuery(div.second)
回答by Rich O'Kelly
If you know the child element you're interested in is the first:
如果您知道您感兴趣的子元素是第一个:
$('.second').children().first();
Or to find by index:
或者按索引查找:
var index = 0
$('.second').children().eq(index);
回答by Deepak Kumar
There are the following way to select first child
有以下方法可以选择第一个孩子
1) $('.second div:first-child')
2) $('.second *:first-child')
3) $('div:first-child', '.second')
4) $('*:first-child', '.second')
5) $('.second div:nth-child(1)')
6) $('.second').children().first()
7) $('.second').children().eq(0)
回答by Samich
You can get first element via index selector:
您可以通过索引选择器获取第一个元素:
$('div.second div:eq(0)')
回答by Magrangs
$('.second').find('div:first')
回答by unaesthetic
Doesn't nth-child return siblings rather than children?
nth-child 不是返回兄弟姐妹而不是孩子吗?
var $selFirst = $(".second:nth-child(1)");
will return the first element with the class '.second'.
将返回类为“.second”的第一个元素。
var $selFirst = $(".selector:nth-child(1)");
should give you the first sibling of class '.selector'
应该给你类 '.selector' 的第一个兄弟
回答by Raynos
var node = document.getElementsByClassName("second")[0].firstElementChild
var node = document.getElementsByClassName("second")[0].firstElementChild
Disclaimer:Browser compliance on getElementsByClassName
and firstElementChild
are shaky. DOM-shims fix those problems though.
免责声明:在浏览器的合规性getElementsByClassName
和firstElementChild
发抖。DOM-shims 解决了这些问题。