Melvin Witte
Melvin Witte

Reputation: 169

DOMParser parseFromString removing nodes only when iterating resulting body childNodes

I am writing an electronjs app. I want to parse a string to DOM nodes and try to use DOMParser parseFromString for that. Here is the code:

let str = '<div id="customerList" style="display: none;"><ul></ul></div><script type="text/javascript" src="../js/customerList.js"></script>';
let nodes = new DOMParser().parseFromString(str, 'text/html').body.childNodes;
console.log(nodes);

This returns a NodeList with 2 elements, the expected div and scriptl, in it. If I add the following part in the code, the first element, the div, disappears from the NodeList:

let str = '<div id="customerList" style="display: none;"><ul></ul></div><script type="text/javascript" src="../js/customerList.js"></script>';
let nodes = new DOMParser().parseFromString(str, 'text/html').body.childNodes;
console.log(nodes);
for (let node of nodes) {
  contentDiv.appendChild(node);
}

The for loop is after the console.log and somehow alters the behavior of the code before. I can't seem to figure out, why the code behaves like it does though...Since I want to provide information about the first element in an ipcRenderer call, this is actually quite frustrating at the moment. Why does the code behave like it does?

Upvotes: 1

Views: 920

Answers (1)

Andreas Dolk
Andreas Dolk

Reputation: 114817

Node.appendChild() moves a node to the new destination. That's why it disappears from your node list.

You can clone the node to avoid that like so:

let str = '<div id="customerList" style="display: none;"><ul></ul></div><script type="text/javascript" src="../js/customerList.js"></script>';
let nodes = new DOMParser().parseFromString(str, 'text/html').body.childNodes;
console.log(nodes);
for (let node of nodes) {
  contentDiv.appendChild(node.cloneNode());
}

This will append clones of all(!) nodes from the list and keep your nodes list as is.

Reference: https://developer.mozilla.org/en-US/docs/Web/API/Node/appendChild

Upvotes: 2

Related Questions