Ad

Getting JavaScript To Create A Full Li

- 1 answer

function loadFamily() {

  var family = ["Kelly", "Paul", "Jason", "Jessica", "Mat"];
  var ulElement = document.getElementById("nameList");

  for (var name in family); 
  {
    var listItem = ulElement.appendChild(document.createElement("li"));
    listItem.appendChild(document.createTextNode(family[name]));
  }

}

I am trying to get this code to create a ul in my html. I have been able to make it work; however it will only place the last name of the array when the page is loaded. This is my first time working with JavaScript and I'm sure that this is a really simple problem, but any help is much appreciated!

Ad

Answer

You are stopping your for loop here:

for (var name in family); 
//----------------------^ Remove this.

It runs fully and the index is in the last, so it executes only the last one now. So change your code to:

function loadFamily() {

  var family = ["Kelly", "Paul", "Jason", "Jessica", "Mat"];
  var ulElement = document.getElementById("nameList");

  for (var name in family) {
    var listItem = ulElement.appendChild(document.createElement("li"));
    listItem.appendChild(document.createTextNode(family[name]));
  }

}

Note: A for...in loop only iterates over enumerable properties. Do not use this for Arrays. It is better to change your loop like:

function loadFamily() {

  var family = ["Kelly", "Paul", "Jason", "Jessica", "Mat"];
  var ulElement = document.getElementById("nameList");

  for (var name = 0; name < family.length; name++) {
    var listItem = ulElement.appendChild(document.createElement("li"));
    listItem.appendChild(document.createTextNode(family[name]));
  }

}

The above is better and good.

Ad
source: stackoverflow.com
Ad