I'm just started with JavaScript and I have a little problem.
How do I use the innerHTML propriety to change the text in this element:
(function showArray(){
  var names = new Array("Bob ","Alice ","Ceaser ","David");
  names.sort();
  for (var i = 0; i < names.length; i++) {
    document.getElementById("loop").innerHTML = names[i];
    // I'm only getting "David" as output!!
  }
})();
<p id="loop">David Alice Bob Ceaser</p>
Try this, you just need to join the names too.
function showArray() {
  var names = new Array("Bob ", "Alice ", "Ceaser ", "David");
  names.sort();
  document.getElementById("loop").innerHTML = names.join(" ");
}
showArray();
<p id="loop">David Alice Bob Ceaser</p>
Just for the record: your code can be reduced to
 (function() {
   document.querySelector("#loop").innerHTML = 
       ["Bob ", "Alice ", "Ceaser ", "David"].sort().join(" ");
 }())
<p id="loop"></p>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With