Andross
Andross

Reputation: 37

Loop through array and retrieve values

I am trying to loop through an array and then loop through a list.

The issue I am having is for each <li> the entire array is being appended, but what I need to happen is index(0) of array gets added to the 1st li, index(1) to the 2nd li and so on.

Code:

// Create our test array.
var arrValues = [ "one", "two", "three" ];

// Loop over each value in the array.
$.each(arrValues,function( intIndex, objValue ){
    $("#list span").each(function() {
        $(this).append(objValue);
    });
});

current output:

<ul id="list">
        <li>Content 1 here<span>onetwothree</span></li>
        <li>Content 2 here<span>onetwothree</span></li>
        <li>Content 3 here<span>onetwothree</span></li>
    </ul>

required output:

<ul id="list">
        <li>Content 1 here<span>one</span></li>
        <li>Content 2 here<span>two</span></li>
        <li>Content 3 here<span>three</span></li>
    </ul>

Appreciate any help :)

Upvotes: 2

Views: 190

Answers (2)

Michael Marr
Michael Marr

Reputation: 2099

I think this would be an easier way to implement:

    $("#list span").each(function( intIndex, objValue ){
        $(this).append(arrValues[intIndex]);
    });

The issue you currently have is you're iterating through the array ( 3 iterations ), and each iteration is looping through the entire number of <span>s, and thus a total of 9 iterations.

Upvotes: 1

Matt Cain
Matt Cain

Reputation: 5768

Just do this:

var arrValues = [ "one", "two", "three" ];

$("#list span").each(function(index) {
    $(this).append(arrValues[index]);
});

Upvotes: 2

Related Questions