0

I am trying to print a list of objects using vanilla javascript. In my loop, only the last item is getting printed. How do I fix this? I tried appending each li to a variable (node) and then append it to my ul id but that did not work. Here is the fiddle:

https://codepen.io/anon/pen/LLgZzw?editors=1011

HTML

<ul id="list"></ul>

JS

let list = document.getElementById('list');

let obj = {
  "codepen": 'www.codepen.io',
  "jsfiddle": 'www.jsfiddle.com',
  "jsbin": 'www.jsbin.com'
};
function printList(obj){
  for(let key in obj){
    console.log(key);
    list.innerHTML = `<li><a href= ${obj[key]}>${key}</a></li>`;
  }
  //list.appendChild(li);
}
printList(obj);
2
  • You need to concatenate your string here list.innerHTML += <li><a href= ${obj[key]}>${key}</a></li>; using += Commented Jul 8, 2017 at 16:41
  • Thanks @Mr.Alien! Commented Jul 8, 2017 at 17:09

1 Answer 1

2

You need to concat value to innerHTML.In your case it is always the last value of the iteration that will be set in innerHTML

let list = document.getElementById('list');

let obj = {
  "codepen": 'www.codepen.io',
  "jsfiddle": 'www.jsfiddle.com',
  "jsbin": 'www.jsbin.com'
};

function printList(obj) {
  for (let key in obj) {
    console.log(key);
    //Changed here. added + before ==.It will concat the current value with previous value
    list.innerHTML += `<li><a href= ${obj[key]}>${key}</a></li>`;
  }
  //list.appendChild(li);
}
printList(obj);
<ul id="list"></ul>

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

1 Comment

exactly what I needed! Thanks a lot @brk

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.