tags:

views:

21

answers:

2

Hiya,

I have a simple set of images nested in a div tag, I'm just wondering how I can chose an item with a specific index programatically?

var n = new Array();
n.push(a);
n.push(b);
n.push(c);

n[1]; // b

How do I do this in JQuery?

Thanks

A: 

Use the :eq(index) selector or the .eq(index) function, like this:

$("#myDiv img:eq(0)")  //get the first one
//equal to: $("#myDiv img").eq(0)
$("#myDiv img:eq(1)") //get the second one
//equal to: $("#myDiv img").eq(1)

Alternatively, there's .get(index) if you want the actual DOM element and not the jQuery (wrapped) element, like this:

$("#myDiv img").get(0)  //get the first one

All of the above options have a zero-based index.

Nick Craver
Fab, thanks for that!
Chris
A: 
var image = $('#div_id img').get(2)
calumbrodie
Thanks, did use this originally but I couldn't call any methods, I'll review my syntax when I have a moment.e.g. I couldn't do var image = $('#div_id img').get(2)image.show();
Chris
@Chris yeah - as Nick alluded to this will return the dom element only and will not have access to jQueries chaining methods.
calumbrodie