Reputation: 130215
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)
<body>
<header>
<div>foo</div>
<div>bar</div>
</header>
</body>
// 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);
Upvotes: 2
Views: 2303
Reputation: 664548
You can use a DocumentFragment
instead of the array:
var nodesFragment = document.createDocumentFragment();
nodesFragment.appendChild(link1);
nodesFragment.appendChild(link2);
nodeToReplace.replaceWith(nodesFragment); // experimental, no good browser support
nodeToReplace.parentNode.replaceChild(nodesFragment, 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.
Upvotes: 9
Reputation: 130215
My initial solution was a straightforward iteration:
// iterate on the Array and insert each element before the one to be removed
for(let node of nodesArr)
nodeToReplace.parentNode.insertBefore(node, nodeToReplace);
// remove the chosen element
nodeToReplace.parentNode.removeChild(nodeToReplace);
Upvotes: 1