Reputation:
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?
Upvotes: 3
Views: 3611
Reputation: 3880
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]);
});
I hope this helps.
Upvotes: 2
Reputation: 253506
You could simply do:
$('p').text(function(i){
return col[i];
});
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];
});
References:
Upvotes: 2
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
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]);
}
Upvotes: 0
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