Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

javascript

dom

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)

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);
like image 816
vsync Avatar asked Jul 27 '26 12:07

vsync


2 Answers

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.

like image 152
Bergi Avatar answered Jul 30 '26 02:07

Bergi


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);
like image 24
vsync Avatar answered Jul 30 '26 02:07

vsync



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!