2

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>

2 Answers 2

1

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".

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

Comments

1

#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".

1 Comment

I was thinking the same thing, but since x is declared before the loop, shouldn't it work?

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.