Reputation: 651
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
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
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:
getElementById
inside a loop. Instead, store the element in a variable before the loop.innerHTML
at each iteration. Instead, update a string variable and only modify innerHTML
after the loop.[]
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
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