javascript - How to set a nodelist as innerHtml? - Stack Overflow

I have a nodelist, nl, and a div#parent. How can I set all elements from nl as div#parent's innerH

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?

Share Improve this question edited Jul 11, 2015 at 5:24 asked Feb 27, 2014 at 13:26 user2953119user2953119 2
  • 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?". – user663031 Commented Jul 11, 2015 at 4:57
  • Check out NodeList.js – Edwin Reynoso Commented Aug 8, 2015 at 13:44
Add a ment  | 

3 Answers 3

Reset to default 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

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

相关推荐

  • javascript - How to set a nodelist as innerHtml? - Stack Overflow

    I have a nodelist, nl, and a div#parent. How can I set all elements from nl as div#parent's innerH

    9小时前
    40

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信