2

I have a nodelist, nl, and a div#parent.

How can I set all elements from nl as div#parent's innerHTML?

  • 1
    Your question is phrased so as to assume the solution involves `innerHTML`, but in fact `innerHTML` is a sort of blunt knife that fills an element with DOM content represented as a huge string. A more general statement of your problem would be "How to set a nodelist as the content of an element?". –  Jul 11 '15 at 04:57
  • Check out [NodeList.js](https://github.com/eorroe/NodeList.js) – Edwin Reynoso Aug 08 '15 at 13:44

3 Answers3

2

Empty the parent first, then use appendChild to append a DOM element

parent.innerHTML = '';
parent.appendChild(nl);

for nodeLists containing several elements, iteration is needed

parent.innerHTML = ''; 

[].forEach.call(nl, function(item) {
    parent.appendChild(item);
});

FIDDLE

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 1
    If `nl` is a NodeList, even if it only contains one node, then `appendChild` will not work. –  Jul 11 '15 at 04:50
  • use [documentFragment](https://stackoverflow.com/a/14910308/3596672) instead of repeatedly calling appendChild to avoid unnecessary document reflow – Aurovrata Nov 03 '21 at 15:45
2

When nodelists are iterables, then you can do

for (let node of nl) parent.appendChild(node);

See Are HTMLCollection and NodeList iterables?. In the meantime, you may have some luck with

NodeList.prototype[Symbol.iterator] = Array.prototype[Symbol.iterator];
Community
  • 1
  • 1
1

Try creating a document fragment and append that instead.

var fragment = document.createDocumentFragment();

while(nl.length) 
    fragment.appendChild(nl[0]);

parent.appendChild(fragment);

Demo

Zach Saucier
  • 24,871
  • 12
  • 85
  • 147
  • 1
    The idea of using a fragment is good, but if the nodelist is "live", as is the case of `childNodes` as used in your fiddle, then this will work, because appending each element to the fragment will remove it from the list. However, if nodelist is **not** live, such as the return from `querySelectorAll`, then you'll end up with an infinite loop. –  Jul 11 '15 at 04:55