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?
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).
In jQuery, you can select multiple elements by separate it with a comma “,” symbol.
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.
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.
You don't need jQuery:
var secondDiv = document.getElementsByTagName('div')[1];
getElementsByTagName('div')
gets an array of all div
s 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
You could also use the nth-child
selector.
http://api.jquery.com/nth-child-selector/
Stangely the :nth-child
did not work for me. I ended up using
$(someElement).find("select").eq(0)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With