let p = document.createElement("p");
let a = document.createElement("a");
for(let i=1; i <= 5; i++) {
p.textContent = i;
a.appendChild(p);
console.log(a);
}
Results
<a><p>5</p></a>
<a><p>5</p></a>
<a><p>5</p></a>
<a><p>5</p></a>
<a><p>5</p></a>
I am struggling to understand this basic concept. I know that when I move the assignment of let p = document.createElement("p");
inside the for loop, I will get the desired result of
<a><p>1</p></a>
<a><p>2</p></a>
<a><p>3</p></a>
<a><p>4</p></a>
<a><p>5</p></a>
I for sure thought that the textContent
property's value will get overwritten by i
but from the first pass-through, i
jumps to 5 right away.
I just want to understand the logic behind this. Thank you and any help is greatly appreciated.