Reputation: 21
I'm still learning basics of js. In this question, my expected result was to get a,b,c,d but it gives a,b,c,c. Can anyone explain? When I put x[3] it prints a,b,c,d.
<p>a</p>
<p>b</p>
<p>c</p>
<p id="demo">d</p>
<script>
var x = document.getElementsByTagName("p");
var i;
for (i = 0; i < x.length; i++) {
document.getElementById("demo").innerHTML = x[i].innerHTML;
}
</script>
Upvotes: 2
Views: 598
Reputation: 89224
#demo
itself is the last element found by document.getElementsByTagName
. Its innerHTML
is first set to the first <p>
element's innerHTML, and then the second's, and then the third's by the loop. At the start of the last iteration, its innerHTML is "c" due to the third paragraph element. It then sets its innerHTML to its own innerHTML, so it ends up staying as "c".
Upvotes: 1
Reputation: 1206
The problem here is that by the time your code loops around to the p tag with the "demo" ID, it reads its own value as "c" since that was what you assigned it in the previous iteration.
So that <p id="demo">d</p>
becomes
a for i=0
b for i=1
c for i=2
When it gets to i=3, it reads the value of itself which is "c", so it reassigns itself to be "c".
Upvotes: 1