Jiang Lan Jiang Lan - 7 months ago 16
Javascript Question

Why my "for" loop only gets the last item in html

I already read JavaScript closure inside loops – simple practical example and Why am I only getting the last item from javascript for loop? but still can't figure out, so I post my code to ask for help

function Produit(nom, prix){
this.nom = nom;
this.prix = prix;
}

// ______________ Objet ____________________

var apple = new Produit("apple", 0.30);
var banana = new Produit("banana", 0.03);
var pear = new Produit("pear", 0.35);
var kiwi = new Produit("kiwi", 0.40);

var produit = [apple,banana,pear,kiwi];


for (var i = 0; i < produit.length; i++) {
$('.test').html(produit[i].nom);
};


html

<div class="test"></div>
<div class="test"></div>
<div class="test"></div>
<div class="test"></div>


The
for
loop only gets the last item name
"kiwi"
in html.

I tested the loop with
console.log
and
alert
and they both get the 4 item names: "apple","banana","pear","kiwi"

Why doesn't this show up in my HTML?

Answer

The problem is you're changing the content of every single element with a test class on every loop iteration. Example:

$('.test').html('Replaced');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>

If you want to change the nth .test element on every loop iteration, you can use .eq.

var list = ['a', 'b', 'c', 'd'];
var $test = $('.test');
for (var i = 0; i < list.length; i++) {
  $test.eq(i).html(list[i]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">1</div>
<div class="test">2</div>
<div class="test">3</div>
<div class="test">4</div>

Comments