3

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?

1
  • Have you missed assigning a value to content[0] or was it left out intentionally?
    – Clyde Lobo
    Commented Jun 13, 2013 at 15:25

1 Answer 1

1

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

1
  • Please consider using textContent (and maybe shim for innerText for IE8) instead of using .innerHTML which is more vulnerable and slower as well. Commented Jun 13, 2013 at 15:13

Your Answer

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