How to log changes to DocumentFragment?

222 Views Asked by At

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>
1

There are 1 best solutions below

2
On BEST ANSWER

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);
});