user1469270
user1469270

Reputation:

For loop not working as expected (with jQuery)

I understand the basic premise of a for loop with JavaScript, however the use of the .each evades me.

var col = [1, 2, 3, 4, 5, 6];

for (var i = 0; i < col.length; i++) {
    $('p').html(col[i]);
}

Which churns out:

<p> 6 </p>
<p> 6 </p>
<p> 6 </p>

When I was expecting:

<p> 1 </p>
<p> 2 </p>
<p> 3 </p>

Why is this not working as expected, and how could it be done with jQuery, rather than pure JavaScript?

http://jsfiddle.net/rgD92/2/

Upvotes: 3

Views: 3611

Answers (5)

danilodeveloper
danilodeveloper

Reputation: 3880

See the code below:

var col = [1, 2, 3, 4, 5, 6];
$('p').each(function(index){
    $(this).text(col[index]);
});

Why your code doesn't work?

When you iterate the "col" list inside the loop, you took all references <p> elements, when the last interaction occurred, the number 6 will be set in all <p> elements.

Update:

If you have more <p> elements than numbers in col list, you can use % operator like the code below:

var col = [1, 2, 3, 4, 5, 6];

$('p').each(function(index){
    $(this).text(col[index % col.length]);
});

Demo

I hope this helps.

Upvotes: 2

David Thomas
David Thomas

Reputation: 253506

You could simply do:

$('p').text(function(i){
    return col[i];
});

JS Fiddle demo.

This will allow jQuery to iterate over the collection itself, rather than using an explicit for loop.

If, as your comment to another answer suggests, you want the col text/contents to loop, should the array be shorter than the number of p elements:

$('p').text(function(i){
    return col[i % col.length];
});

JS Fiddle demo.

References:

Upvotes: 2

benjamin.d
benjamin.d

Reputation: 2881

Using jQuery and each(), you could do:

var col = [1, 2, 3, 4, 5, 6];
$("p").each(function(i) {
    $(this).html(col[i]);
});

Upvotes: 1

Enam
Enam

Reputation: 1268

Your $('p') selector selects all p's on page and your loop updates all p's too.

var col = [1, 2, 3, 4, 5, 6];

for (var i = 0; i < col.length; i++) {
    $('p:eq(' + i + ')').html(col[i]);
}

JSFiddle

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388446

You need to select which p to be updated also, in every iteration you are updating all the p elements in the document.

In the given sample you can use .eq() to select the p element sequentially.

for (var i = 0; i < col.length; i++) {
    $('p').eq(i).html(col[i]);
}

Demo: Fiddle

Upvotes: 2

Related Questions