Paul Murphy
Paul Murphy

Reputation: 25

How to loop through an array and set of dom elements and add the current item of the array to the current dom element?

I have a Jquery array holding 4 strings:

var myArray = [ 1, 2, 3, 4 ];

In my markup I have 4 empty div's with other random markup dispersed intermittently between them.

<div></div>
<p>Paragraph here</p>
<p>Paragraph here</p>
<div></div>
<h1>heading here</h1>
<p>Paragraph here</p>
<div></div>
<h1>heading here</h1>
<p>Paragraph here</p>
<div></div>

I want to loop through the array and also loop through the div's and add the text of the current item in the array to the current div. The end result in my markup should be something like this:

<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>

Not a javascript expert as you can probably tell, so any help would be greatly appreciated. Thanks!

Upvotes: 2

Views: 1403

Answers (2)

shem86
shem86

Reputation: 478

if you don't care for array being empty afterwards you could use:

var myArray = [ 1, 2, 3, 4 ];

$('div').each( function () {
    this.innerHTML = myArray.shift();
});

Upvotes: 1

Sergio
Sergio

Reputation: 28837

Try this:

var myArray = [ 1, 2, 3, 4 ];
$('div').each(function(index){
    this.innerHTML = myArray[index];
});

Demo here

Upvotes: 6

Related Questions