Javascript 如何在网页中使用 jQuery 选择第二个 div?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14071742/
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 select second div using jQuery in a webpage?
提问by Mobi
If a webpage has 2 div tags like
如果一个网页有 2 个 div 标签,例如
<div>hello</div>
<div>hello</div>
How could I select second div, is it possible using jQuery?
如何选择第二个 div,是否可以使用 jQuery?
回答by Chase
回答by Cerbrus
You don't need jQuery:
你不需要jQuery:
var secondDiv = document.getElementsByTagName('div')[1];
getElementsByTagName('div')gets an array of all divs on the page, then you get the second element out of that (zero-indexed) array with [1].
getElementsByTagName('div')获取div页面上所有s的数组,然后使用[1].
You could also apply a jQuery wrapper, if you need jQuery functionality:
如果您需要 jQuery 功能,您还可以应用 jQuery 包装器:
var $secondDiv = $(document.getElementsByTagName('div')[1]); //($ in the var name is merely used to indicate the var contains a jQuery object)
回答by BastiBen
You could also use the nth-childselector.
您也可以使用nth-child选择器。
回答by pat capozzi
Stangely the :nth-childdid not work for me. I ended up using
Stangely:nth-child对我不起作用。我最终使用
$(someElement).find("select").eq(0)
$(someElement).find("select").eq(0)

