vsync vsync - 4 months ago 14
Javascript Question

DOM - Replace node with an array of nodes (efficiently)

What would be an efficient way to replace a DOM node with an array of nodes?

(which are a simple array of detached nodes and not HTMLCollection)

(Please no jQuery answers, only DOM API)

Demo page




// generate simple dummy array of detached DOM nodes

var link1 = document.createElement('a');
link1.innerHTML = 'xxx';

var link2 = document.createElement('a');
link2.innerHTML = 'yyy';

var nodesArr = [link1, link2];

// get the element to replace at some place in the DOM.
// in the case, the second <div> inside the <header> element
var nodeToReplace = document.querySelectorAll('header > div')[1];

// replace "nodeToReplace" with "nodesArr"
for(let node of nodesArr)
nodeToReplace.parentNode.insertBefore(node, nodeToReplace);


You can use a DocumentFragment instead of the array:

var nodesFragment = document.createDocumentFragment();

nodeToReplace.replaceWith(nodesFragement); // experimental, no good browser support
nodeToReplace.parentNode.replaceChild(nodesFragement, nodeToReplace); // standard

However, just inserting multiple elements in a loop shouldn't be much different with regard to performance. Building a document fragment from an existing array might even be slower.