Unable to use global variable with createElement inside loop

21 Views Asked by At

I am unable to create a global variable for a document.createElement('br') object and reuse it inside loops. In the example, I show where can:

  • Example 0: Call document.createElement('br') each time inside the loop, and each line of the output has a break.
  • Example 1: Create a variable for document.createElement('br') each time inside the loop and use it, and each line of the output has a break.
  • Example 2: When the variable for document.createElement('br') is created globally and used inside loop, the output is displayed with no breaks, "a: 1b: 2c: 3"

const obj = { a: 1, b: 2, c: 3 };

/* Does work */
const div0 = document.getElementsByTagName('div')[0];
Object.keys(obj).forEach(key => div0.append(`${key}: ${obj[key]}`, document.createElement('br')))


/* Does work */
const div1 = document.getElementsByTagName('div')[1];
Object.keys(obj).forEach(key => {
    const br1 = document.createElement('br');
    div1.append(`${key}: ${obj[key]}`, br1);
    console.log(`${typeof(br1)}, ${br1}`, br1); // Used to verify I see the same results each time loop is run, and same results as br2
})

/* Does NOT work */
const div2 = document.getElementsByTagName('div')[2];
const br2 = document.createElement('br');
Object.keys(obj).forEach(key => {
    div2.append(`${key}: ${obj[key]}`, br2);
    console.log(`${typeof(br2)}, ${br2}`, br2); // Used to verify I see the same results each time loop is run, and same results as br1
})
<div>Example 0: br Does work - createElement is called each time loop is run.<br></div><br>
<div>Example 1: br Does work - createElement is assigned to a variable each time loop is run.<br></div><br>
<div>Example 2: br Does NOT work - createElement is assigned to a global variable.<br></div>

Why is this not working, which would allow me to create once and reuse? I also included some console.log output to show I am getting the same results for the varible itself in the working & not working examples.

0

There are 0 best solutions below