I would like to convert the following string to DOM structure.
text node <div>div node</div>text node<p>paraph node</p> text node
One approach is,
mydiv = document.createElement('div');
mydiv.innerHTML = 'text node <div>div node</div>text node<p>paraph node</p> text node';
In this approach, the DOM structure is wrapped by another div, which is not i wanted.
After do searching and reading, I found document.createDocumentFragment() is the best way, because when append a fragment to node, it just append fragment's childNodes, not fragment itself
unfortunately, innerHTML method is not available in a fragment.
what should i do? thanks
Try this:
var frag = document.createDocumentFragment();
var mydiv = document.createElement('div');
mydiv.innerHTML = 'text node <div>div node</div>text node<p>paraph node</p> text node';
while( mydiv.firstChild ) {
frag.appendChild( mydiv.firstChild );
}
document.body.appendChild( frag );
I tried all the solutions on this page and none were working sufficiently for my case (a more complex HTML string). I ended using this very simple approach with insertAdjacentHTML that I found here: https://stackoverflow.com/a/7327125/388412
div.insertAdjacentHTML( 'beforeend', str );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With