4

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>

1
  • 4
    Change innerHTML = to innerHTML +=. Commented Oct 11, 2014 at 18:21

3 Answers 3

8

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>

Sign up to request clarification or add additional context in comments.

3 Comments

This answer works, but if your intention is to just put text into a DOM node, you should use innerText instead of innerHTML. It's a good habit that may save you from code-injection attacks in the future, even though it doesn't matter in this example.
@RaphaelSerota innerText isn't standard. It should be textContent.
Oops, my bad. Either way, the point is that you should be mindful of what you allow users to inject into the DOM.
1

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>

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.