vsync vsync - 1 year ago 107
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);

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download