Rene Limon Rene Limon - 3 months ago 8
Javascript Question

jquery each() and js array not working as expected

I have this code in html:

<div class="box-content">
<span>
<h4 id="title">title1</h4>
<h5 id="texto"></h5>
</span>
<span>
<h4 id="title">title2</h4>
<h5 id="texto"></h5>
</span>
<span>
<h4 id="title">title3</h4>
<h5 id="texto"></h5>
</span>
....
</div>


and I need to populate that structure using an array as follows

$(".pluscontrol").click(function(){
var itemBoxValues1 = ["text1", "text2", "text3"];
var i = 0;
$('.box-content').children().each(function(){
var tmp = itemBoxValues1[i];
$('.box-content').children().children("h5").text(" id: "+i+" val "+tmp);
i++;
});
});


but it doesn't work as I expected because in all
<h5>
elements print this:

<span>
<h4 id="title">title n </h4>
<h5 id="texto">id: 35 val 23</h5>
</span>


I don't understand why it's happen. Thanks.

Answer

Try this:

$(".pluscontrol").click(function(){
    var itemBoxValues1 = ["text1", "text2", "text3"];
    var i = 0;
    $('.box-content').children().each(function(){
        var tmp = itemBoxValues1[i];
        $(this).children("h5").text(" id: "+ i +" val "+ tmp);
        i++;
    });
});

Update

Inside each, you need to find children of current span, so you need to use $(this), this $('.box-content').children().children("h5") will return all h5 tags

Also you can use following to save some lines of your code:

var itemBoxValues1 = ["text1", "text2", "text3"];

$('.box-content > span').each(function(i, span){    
    $(span).children("h5").text(" id: "+ i +" val "+ itemBoxValues1[i]);    
});
Comments