vsync vsync - 2 months ago 8
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



HTML



<body>
<header>
<div>foo</div>
<div>bar</div>
</header>
</body>


JS



// 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);
nodeToReplace.parentNode.removeChild(nodeToReplace);

Answer

You can use a DocumentFragment instead of the array:

var nodesFragment = document.createDocumentFragment();
nodesFragment.appendChild(link1);
nodesFragment.appendChild(link2);

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.

Comments