最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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

发布评论

评论列表(0)

  1. 暂无评论