2

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!

2

2 Answers 2

6

Try this:

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

Demo here

Sign up to request clarification or add additional context in comments.

3 Comments

OP wants to fill the <div>s
+1, great answer. You should include a link to the jQuery API for .each(), though.
@Sergio Perfect, thanks I appreciate it. I'll mark as answered.
1

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();
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.