Spoofy
Spoofy

Reputation: 651

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>

Upvotes: 4

Views: 40550

Answers (3)

KooiInc
KooiInc

Reputation: 122906

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>

Upvotes: 1

Oriol
Oriol

Reputation: 288080

In this case, better use Array.prototype.join as suggested in @DaveChen's answer.

However, you can't always use that. For those cases:

  • DOM operations are slow. Therefore,
    • Don't use getElementById inside a loop. Instead, store the element in a variable before the loop.
    • Don't modify innerHTML at each iteration. Instead, update a string variable and only modify innerHTML after the loop.
  • Creating arrays using [] is faster than with Array constructor, and it's shorter.

However, note that using innerHTML may produce html injection. If you just want to add text, better use textContent instead.

(function showArray(){
  var names = ["Bob ","Alice ","Ceaser ","David"],
      el = document.getElementById("loop"),
      html = '';
  names.sort();
  for (var i = 0; i < names.length; i++) html += names[i];
  el.textContent = html;
})();
<p id="loop">David Alice Bob Ceaser</p>

Upvotes: 0

Dave Chen
Dave Chen

Reputation: 10975

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>

Upvotes: 8

Related Questions