Search code examples
javascriptarrayssortinginnerhtmlhtmlcollection

Output HTML collections as a list JavaScript


I'm Trying to turn HTML element contents into a list using JavaScript. I'm using this code but it's only returning the last option - "option 6" - instead of each option line by line.

Can someone tell me what I'm missing please?

  var getOptions = document.getElementsByClassName("aofi");
var i;

for (i = 0; i < getOptions.length; i++) {

  document.getElementById("NewOutput").innerHTML = "<li>" + getOptions[i].innerHTML + "</li>";
}
<div class="allOptions">
  <h2 class="aofi">option 1</h2>
</div>
<div class="allOptions">
  <h2 class="aofi">option 2</h2>
</div>
<div class="allOptions">
  <h2 class="aofi">option 3</h2>
</div>
<div class="allOptions">
  <h2 class="aofi">option 4</h2>
</div>
<div class="allOptions">
  <h2 class="aofi">option 5</h2>
</div>
<div class="allOptions">
  <h2 class="aofi">option 6</h2>
</div>

<div id="NewOutput"></div>


Solution

  • document.getElementById("NewOutput").innerHTML is a property of your element. If you assign a value to this property, the old value will be overwritten.

    You should use

    document.getElementById("NewOutput").innerHTML += "<li>" + 
    //---------------------------------------------^
      getOptions[i].innerHTML + "</li>";
    }
    

    Thus you will add to the innerHTML rather than overwrite it

    P.S. a += b is a shortcut for a = a + b