How can I convert an Array of nodes to a static NodeList?

后端 未结 4 408
轻奢々
轻奢々 2020-12-08 10:02

NOTE: Before this question is assumed a duplicate, there is a section at the bottom of this question that addresses why a few similar questions do not provide the answer

4条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-08 10:04

    You can use outerHTML property of each element, and add it to a parent element (that will create by document.createElement(), the element type doesn't matter). For example, in ES6:

    function getNodeList(elements) {
      const parentElement = document.createElement('div');
      // This can be a differnet element type, too (but only block (display: block;) element, because it impossible to put block element in inline element, and maybe 'elements' array contains a block element).
      let HTMLString = '';
      for (let element of elements) {
        HTMLString += element.outerHTML;
      }
    
      parentElement.innerHTML = HTMLString;
    
      return parentElement.childNodes;
    }
    

提交回复
热议问题