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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:38:36  来源:igfitidea点击:

How to select second div using jQuery in a webpage?

javascriptjquery

提问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

The following will get the second div using the eqmethod:

以下将使用该eq方法获取第二个 div :

$("div:eq(1)");

EXAMPLE

例子

Please note that @Cerbrus's answer is also correct, you can do this without jQuery.

请注意@Cerbrus 的回答也是正确的,您可以在没有 jQuery 的情况下执行此操作。

回答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)

Example

例子

回答by BastiBen

You could also use the nth-childselector.

您也可以使用nth-child选择器。

http://api.jquery.com/nth-child-selector/

http://api.jquery.com/nth-child-selector/

回答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)