Yogesh Ghaturle
Yogesh Ghaturle

Reputation: 267

Using variable inside array.push() in jquery

I have a for loop in my jquery script

var images[];
for(i=0;i<$('#imageHolder div').length;i++)
{
    images.push($('#imageHolder div:eq( i )').attr('alt'));
    console.log($('#imageHolder div:eq(i )').attr('alt'));
}

I am not able to add the elements to the array and the console.log says undefined in the console. What is my possible error and how that can be corrected?

Upvotes: 1

Views: 270

Answers (3)

dfsq
dfsq

Reputation: 193291

jQuery has useful method for this task, called $.fn.map:

var images = $('#imageHolder div').map(function() {
    return $(this).attr('alt');
}).get();

Will produce an array of images alt attributes.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388406

i is a variable so need to use concatenation

$('#imageHolder div:eq('+  i + ')').attr('alt')

A more efficient way is to use .map(), in your case you are evaluating the selector many times which is not a optimal way

var images = $('#imageHolder div').map(function () {
    return $(this).attr('alt')
}).get()

Upvotes: 0

Pierrickouw
Pierrickouw

Reputation: 4704

You have a typo:

images.push($('#imageHolder div:eq(' + i + ')').attr('alt')); 
                 you need to concat i ^^^^

By the way, don't select your element every time in the for

var divs = $('#imageHolder div');
for(i=0; i < divs.length; i++)

Upvotes: 0

Related Questions