最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Trouble using JavaScript for loop to populate an array with HTML divs - Stack Overflow

programmeradmin3浏览0评论

I'm trying to populate the contents of an array with the HTML from 5 different div elements using a loop. I can't get the for loop to work correctly. Any ideas?

The HTML:

<div id="person0">John</div>
<div id="person1">Kathleen</div>
<div id="person2">Cynthia</div>
<div id="person3">Eric</div>
<div id="person4">Jay</div>



<div style="width: 600px; margin: auto; padding: 15px; border: 1px solid gray; font-family: sans-serif;">
        <h1>The People</h1>
        <div id="result"></div>
</div>

The Javascript:

function pageLoaded(){

  var list = "<ul>";
  var myArray = new Array();

  for(i=0; i<6; i++){
    var person = "person";
    var personNumber = "" + i.toString();
    var divId = person.concat(personNumber);
    myArray[i] = document.getElementById(divId).innerHTML;
    list +="<li>"+myArray[i]+"</li>";
  }


  list +="</ul>";

  document.getElementById("result").innerHTML=list;

}

I'm trying to populate the contents of an array with the HTML from 5 different div elements using a loop. I can't get the for loop to work correctly. Any ideas?

The HTML:

<div id="person0">John</div>
<div id="person1">Kathleen</div>
<div id="person2">Cynthia</div>
<div id="person3">Eric</div>
<div id="person4">Jay</div>



<div style="width: 600px; margin: auto; padding: 15px; border: 1px solid gray; font-family: sans-serif;">
        <h1>The People</h1>
        <div id="result"></div>
</div>

The Javascript:

function pageLoaded(){

  var list = "<ul>";
  var myArray = new Array();

  for(i=0; i<6; i++){
    var person = "person";
    var personNumber = "" + i.toString();
    var divId = person.concat(personNumber);
    myArray[i] = document.getElementById(divId).innerHTML;
    list +="<li>"+myArray[i]+"</li>";
  }


  list +="</ul>";

  document.getElementById("result").innerHTML=list;

}
Share Improve this question edited Feb 24, 2013 at 2:03 elclanrs 94.2k21 gold badges137 silver badges171 bronze badges asked Feb 24, 2013 at 1:59 maiamachinemaiamachine 2804 silver badges14 bronze badges 3
  • 2 I know it's not an answer, but have you looked into using jQuery? It makes JavaScript development much easier and more elegant. – Philip Tenn Commented Feb 24, 2013 at 2:04
  • I've definitely thought about that but I'm trying to get better at JS functions so sort of doing this for practice :) – maiamachine Commented Feb 24, 2013 at 2:05
  • good for you on practicing core JS, best wishes with that. Tossed together a page with your HTML and JavaScript, with some alerts, got it working. – Philip Tenn Commented Feb 24, 2013 at 2:14
Add a ment  | 

5 Answers 5

Reset to default 3

Just change the for condition from i<6 to i<5.

You were running the loop one too many times, which meant on the sixth iteration when you did:

myArray[i] = document.getElementById(divId).innerHTML;

You were looking for an element with id of "person5", so getElementById() returned null which gave the error:

Uncaught TypeError: Cannot read property 'innerHTML' of null 

...which stopped your script from pleting.

Demo: http://jsbin./awubeq/1/edit

Here's a working solution (plus some alerts):

<html>
<head>
   <title>Test</title>
   <script>

function pageLoaded()
{
  alert("called pageLoaded");
  var list = "<ul>";
  var myArray = new Array();

  for(i=0; i<5; i++){
    var person = "person";
    var personNumber = "" + i.toString();
    var divId = person.concat(personNumber);
    myArray[i] = document.getElementById(divId).innerHTML;
    alert("myArray[i]=" + myArray[i]);
    list +="<li>"+myArray[i]+"</li>";

  }


  list +="</ul>";

  alert(list);


  document.getElementById("result").innerHTML=list;

}
</script>
</head>

<body onload="pageLoaded()">

<div id="person0">John</div>
<div id="person1">Kathleen</div>
<div id="person2">Cynthia</div>
<div id="person3">Eric</div>
<div id="person4">Jay</div>



<div style="width: 600px; margin: auto; padding: 15px; border: 1px solid gray; font-family: sans-serif;">
        <h1>The People</h1>
        <div id="result"></div>
</div>

</body>
</html>

If you use an iterator, you don't have to worry about knowing the size of the target of iteration.

document.getElementById('result').innerHTML =
Array.prototype.reduce.call(document.querySelectorAll('[id^=person]'),
    function (prev, elem) {
       return prev + '<li>' + elem.innerHTML + '</li>';
}, '<ul>') + '</ul>';

http://jsfiddle/ExplosionPIlls/Avfjs/1/

You are looping thru more divs than you have. If you switch it to 4, it works.

for(i=0; i<5; i++){

or 

for(i=0; i<=4; i++){

Since you are practicing, I just wanted to point out that you should reconsider the markup as this is not a case for using an id attribute but for a class. The id approach, though mon, is incorrect and requires more code than necessary. Here is an example with better markup, which makes using javascript with it much more straightforward.

http://jsfiddle/3gpe8/

发布评论

评论列表(0)

  1. 暂无评论