Skip to main content
Inspiring
January 31, 2012
Question

Jquery Array

  • January 31, 2012
  • 1 reply
  • 461 views

I'm trying  to teach myself Jquery. Im having a bit of a problem with arrays.

I have a div loaded up with a couple of images. I can get the length of the images in the div (Could you consider the items in the div as an array with the items inside, because it has a length?)

I cant seem to figure out how to get at any of items in the array. Once I can figure how to get an item (index) in the array, I'll figure out how to use the for loop to do something with the individual item

<div id="imgholder">

<img src="guy.jpg"/>

<img src="guy.jpg"/>

</div>

*wasn't sure if this was a good place to ask jquery questions.

           Thanks

This topic has been closed for replies.

1 reply

David_Powers
Inspiring
February 1, 2012

Not quite sure what you want to do with the images, but you can either treat them as a jQuery wrapped set or convert them to a DOM array.

For example, the following displays the source of the image using the jQuery each() method:

$(function() {

    var pix = $('#imgholder').children('img');

    pix.each(function(i) {

        alert(this.src);

    });

});

Inside the function passed to each(), "this" refers to the current image.

Using a DOM array, the following does the same:

$(function() {

    var pix = $('#imgholder').children('img').toArray();

    for (var i = 0; i < pix.length; i++) {

        alert(pix.src);

    }

});

In this case, pix is a standard array, so you access each one as pix, i being the loop counter.