Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript array and innerHTML

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>
like image 653
Spoofy Avatar asked Jan 09 '23 15:01

Spoofy


2 Answers

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>
like image 53
Dave Chen Avatar answered Jan 12 '23 07:01

Dave Chen


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>
like image 30
KooiInc Avatar answered Jan 12 '23 08:01

KooiInc