Adrian Adrian - 3 months ago 23
jQuery Question

append array values to multiple divs in order

I'm trying to replace all titles from

.item
with the values from
array
. This is the array:

var itCats = ['one', 'two', 'three', 'four'];


and the html:

<div class="item it1">
<p>title 1</p>
</div>
<div class="item it2">
<p>title 2</p>
</div>
<div class="item it3">
<p>title 3</p>
</div>
<div class="item it4">
<p>title 4</p>
</div>


Tried with this but I gor script error and browser closed.

for (var i = itCats.length; i--;) {
//arr[i] = '#' + arr[i];
for (var i = 0; i < $(".item").length; i++) {
$(".item p').html('itCats[i]);
}
}

Answer

You messed up a few tings. The easiest solution for your result is a each loop and use the index by the callback.

$('.item p').each(function(index) {
    $(this).text(itCats[index]);
});

var itCats = ['one', 'two', 'three', 'four'];

$('.item p').each(function(index) {
    $(this).text(itCats[index]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="item it1">
    <p>title 1</p>
</div>
<div class="item it2">
    <p>title 2</p>
</div>
<div class="item it3">
    <p>title 3</p>
</div>
<div class="item it4">
    <p>title 4</p>
</div>

You can even use a callback of text or html:

$('.item p').text(function(index) {
    return itCats[index];
});

var itCats = ['one', 'two', 'three', 'four'];

$('.item p').text(function(index) {
    return itCats[index];
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="item it1">
    <p>title 1</p>
</div>
<div class="item it2">
    <p>title 2</p>
</div>
<div class="item it3">
    <p>title 3</p>
</div>
<div class="item it4">
    <p>title 4</p>
</div>

Or to show another solution, as arrow function:

$('.item p').text(i => itCats[i]);

var itCats = ['one', 'two', 'three', 'four'];
$('.item p').text(i => itCats[i]);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="item it1">
    <p>title 1</p>
</div>
<div class="item it2">
    <p>title 2</p>
</div>
<div class="item it3">
    <p>title 3</p>
</div>
<div class="item it4">
    <p>title 4</p>
</div>