Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select second div using jQuery in a webpage?

If a webpage has 2 div tags like

<div>hello</div>
<div>hello</div>

How could I select second div, is it possible using jQuery?

like image 320
Mobi Avatar asked Dec 28 '12 15:12

Mobi


People also ask

Which of the following CSS selectors will select the second div in jQuery?

myclass:eq(1)" ) selects the second element in the document with the class myclass, rather than the first. In contrast, :nth-child(n) uses 1-based indexing to conform to the CSS specification. Prior to jQuery 1.8, the :eq(index) selector did not accept a negative value for index (though the . eq(index) method did).

Can you select multiple elements in jQuery?

In jQuery, you can select multiple elements by separate it with a comma “,” symbol.

How do you select elements in jQuery?

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element. An id should be unique within a page, so you should use the #id selector when you want to find a single, unique element.


4 Answers

The following will get the second div using the eq method:

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

EXAMPLE

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

like image 153
Chase Avatar answered Oct 19 '22 14:10

Chase


You don't need 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].

You could also apply a jQuery wrapper, if you need jQuery functionality:

var $secondDiv = $(document.getElementsByTagName('div')[1]); //($ in the var name is merely used to indicate the var contains a jQuery object)

Example

like image 37
Cerbrus Avatar answered Oct 19 '22 15:10

Cerbrus


You could also use the nth-child selector.

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

like image 1
BastiBen Avatar answered Oct 19 '22 13:10

BastiBen


Stangely the :nth-child did not work for me. I ended up using

$(someElement).find("select").eq(0)

like image 1
pat capozzi Avatar answered Oct 19 '22 14:10

pat capozzi