I have a nodelist, nl
, and a div#parent
.
How can I set all elements from nl
as div#parent
's innerHTML
?
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 factinnerHTML
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?". – user663031 Commented Jul 11, 2015 at 4:57 - Check out NodeList.js – Edwin Reynoso Commented Aug 8, 2015 at 13:44
3 Answers
Reset to default 2Empty 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
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];
Try creating a document fragment and append that instead.
var fragment = document.createDocumentFragment();
while(nl.length)
fragment.appendChild(nl[0]);
parent.appendChild(fragment);
Demo
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745196839a4616136.html
评论列表(0条)