1

My solution: https://jsfiddle.net/c96hv9tj/1/

function filler(list, arr){
    let b = document.createElement("li");

    for(let i = 0; i < arr.length; i++){
        b.appendChild(document.createTextNode(arr[i]));
    } 
    list.appendChild(b);
}

I'm trying to make it create a new li for each index from the array help please.

2 Answers 2

4

You need to put everything inside the loop like this :

function filler(list, arr) {

  for (let i = 0; i < arr.length; i++) {
    let b = document.createElement("li");
    b.appendChild(document.createTextNode(arr[i]));
    list.appendChild(b);
  }

}


let ul = document.getElementById("fillthislist");
let entries = ["Shmi", "Anakin", "Luke"];

filler(ul, entries);
<section>
  <h1>Fill an empty list with the contents of an array</h1>
  <ul id=fillthislist>
  </ul>
</section>

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

Comments

0

For better performance don't appendChild to the document element. Use a Document Fragment instead.

function filler(list, listItems) {

  var fragment = document.createDocumentFragment();

  listItems.forEach(item => {
    let li = document.createElement('li');
    li.appendChild(document.createTextNode(item));
    fragment.appendChild(li);
  });

  list.appendChild(fragment);
}

Since the document fragment is in memory and not part of the main DOM tree, appending children to it does not cause page reflow (computation of element's position and geometry). Consequently, using document fragments often results in better performance.


JsFiddle example:
https://jsfiddle.net/c96hv9tj/11/

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.