Search code examples
javascripthtmlappendchild

How to pull all headings textContents out of HTML and make a <ul> list out of them?


For a blog I want to create a side navigation bar which will pull all blog post titles (written in <h2>'s) and list them inside a <ul>. Here's what I have so far, but for some reason it puts all the headings textContents into a single <li>, instead of creating separate <li>'s per heading. Can anyone tell why? I can't figure it out for some reason...

js.fiddle

document.addEventListener('DOMContentLoaded', () => {
  var ul = document.getElementById("sideNav");
  var li = document.createElement("li");
  var h2 = document.getElementsByTagName("h2");
  for (var i = 0; i < h2.length; i++) {
    li.appendChild(document.createTextNode(h2[i].textContent));
    ul.appendChild(li);
  }
})
<h2>Header 1</h2>
<h2>Header 2</h2>
<h2>Header 3</h2>
<h2>Header 4</h2>
<ul id="sideNav"></ul>


Solution

  • You are only creating a single li element, but you need one for each headline. Move the line

    var li = document.createElement("li");
    

    inside the loop and it will work.