user2375017
user2375017

Reputation:

How to fill an array of divs with values from another array?

I've got eight divs, which I've put into a JavaScript array. I've also got another array of eight different strings. basically I want the strings from one array to be displayed in the divs from the first array.

I'm fairly new to JavaScript so I'm having a hard time getting my head round it. Would I need to use loops?

Eventually the strings in the content array will be fed by a PHP script.

This is what I've come up with at the moment:

var content = [] ;
      content[1] = "More Lessons about the Q 'ran in RS!"; 
      content[2] = "'fralalalalalala'"; 
      content[3] = "'Information about how to write a letter properly'";
      content[4] = "'This is number four'";
      content[5] = "'This is number five'";
      content[6] = "'This is number six'";
      content[7] = "'This is number seven'";
      content[8] = "'This is number eight'";


  var alldivs = [];
  alldivs[alldivs.length] = document.getElementsByClass("resize");

  for(i=0 ; i<= alldivs.length && content.length; i++) 
  {
    alldivs[i].value = content[i];
  }

But that doesn't work. Anybody know how I could achieve this?

Upvotes: 3

Views: 205

Answers (1)

Yotam Omer
Yotam Omer

Reputation: 15376

try: (jsFiddle)

 var alldivs = document.getElementsByClassName("resize");

 ...

 for(i=0 ; ((i <= alldivs.length) && (i <= content.length)); i++) {
        alldivs[i].innerHTML = content[i];
 }

you used getElementsByClass instead of getElementsByClassName and value instead of innerHTML or innerText, also, you need to start your content indexes from 0 because alldivs array will start from 0

Upvotes: 1

Related Questions