avi dahan
avi dahan

Reputation: 559

Parsing Html from string into document

I'm trying to parse Html code from string into a document and start appending each node at a time to the real dom. After some research i have encountered this api :

DOMImplementation.createHTMLDocument()

which works great but if some node has descendants than i need to first append the node and only after its in the real dom than i should start appending its descendants , i think i can use

document.importNode(externalNode, deep);

with the deep value set to false in order to copy only the parent node. so my approach is good for this case and how should i preserve my order of appended nodes so i wont append the same node twice? and one more problem is in some cases i need to add more html code into a specific location (for example after some div node) and continue appending , any idea how to do that correctly?

Upvotes: 1

Views: 254

Answers (1)

Paul Varache
Paul Varache

Reputation: 53

You can use the DOMParser for that:

const parser = new DOMParser();
const doc = parser.parseFromString('<h1>Hello World</h1>', 'text/html');

document.body.appendChild(doc.documentElement);

But if you want to append the same thing multiple times, you will have better performances using a template:

const template = document.createElement('template');
template.innerHTML = '<h1>Hello World</h1>';
const instance = template.cloneNode(true);
document.body.appendChild(instance.content);
const instance2 = template.cloneNode(true);
document.body.appendChild(instance2.content);

Hope this helps

Upvotes: 1

Related Questions