Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop DOM basics?

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.

like image 502
Rumba Avatar asked Aug 04 '26 15:08

Rumba


1 Answers

If you leave the declaration of p outside the loop, then the element object is created only once, whereas if you put it inside the loop, a new object is created with each iteration.

The reason for what you're seeing in the first case is that p is a single object, which you are appending to a again and again. Since it is the same object, modifying it changes it everywhere.

In the second case, you have multiple distinct element objects which you are appending to a. Modifying one has no effect on the others.

EDIT: This happens because console.log actually logs after the loop as completed, as mentioned by Patrick Evans in the comments.

Also, did you notice that a always has one element, even though we call appendChild on it multiple times?

If you want to have multiple distinct p elements, but a single p object which gets incremented, then this code should work:

let p = document.createElement("p");
let a = document.createElement("a");

for(let i=1; i <= 5; i++) {
    p.textContent = i;      
    a.appendChild(p.cloneNode(true));
    console.log(a);
}
like image 181
stelioslogothetis Avatar answered Aug 07 '26 06:08

stelioslogothetis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!