user2953119
user2953119

Reputation:

How to set a nodelist as innerHtml?

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

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

Upvotes: 2

Views: 4448

Answers (3)

user663031
user663031

Reputation:

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];

Upvotes: 2

adeneo
adeneo

Reputation: 318222

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

Upvotes: 2

Zach Saucier
Zach Saucier

Reputation: 25954

Try creating a document fragment and append that instead.

var fragment = document.createDocumentFragment();

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

parent.appendChild(fragment);

Demo

Upvotes: 1

Related Questions