1

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I know about the DOMParser api but it doesn't solve any of the problems i mentioned in my question so unfortunately it wont help me at all
Sorry this didn't help. I think I don't understand fully your question then. Appending content to a DOM tree from a string is pretty straightforward using the methods I showed you. This can add a whole sub-tree directly with the order preserved. If for some reason you need to append all the nodes manually as you mentioned, you will have to use a TreeWalker and write the append logic yourself. It is usually a anti-pattern to do so as it does not alleviates the performant string parsing from the browser itself
i do need to append each node separately and if the node contains childrens then i need to append the node without its childrens and then start appending its childrens and so on...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.