1

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?

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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++)

Comments

0

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.