1

When I run the following code in the browser -

const frag = new DocumentFragment();
const ul = document.createElement('ul');
frag.appendChild(ul);
Object.entries(['a', 'b', 'c']).forEach(([key, value]) => {
  const li = document.createElement('li');
  li.textContent = value;
  ul.appendChild(li);
  console.log(key, frag.firstChild);
});

3 unordered lists are logged each with 3 list item elements -

0
<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>
1
<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>
2
<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>

How can I log the progression as elements are added to the list. For example -

0
<ul>
  <li>a</li>
</ul>
1
<ul>
  <li>a</li>
  <li>b</li>
</ul>
2
<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>
user2309803
  • 541
  • 5
  • 15

1 Answers1

1

You can do this by logging the HTML content of ul element, not its reference, for this you can use outerHTML:

const frag = new DocumentFragment();
const ul = document.createElement('ul');
frag.appendChild(ul);
Object.entries(['a', 'b', 'c']).forEach(([key, value]) => {
  const li = document.createElement('li');
  li.textContent = value;
  ul.appendChild(li);
  console.log(key, frag.firstChild.outerHTML);
});
n--
  • 3,563
  • 4
  • 9
  • Thanks, your solution works. Just for my information - why does the reference not work? It points to the `UL` which at the time of the first `console.log` only had one list item element, not three. – user2309803 May 02 '22 at 06:00
  • This is because of "live view" feature of console, as noted [here](https://developer.mozilla.org/en-US/docs/Web/API/console/log#logging_objects) – n-- May 02 '22 at 22:14