Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert innerHTML string to DOM structure in javascript

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

like image 270
wukong Avatar asked Jul 08 '26 15:07

wukong


2 Answers

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 );
like image 143
Esailija Avatar answered Jul 11 '26 05:07

Esailija


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 );
like image 42
auco Avatar answered Jul 11 '26 04:07

auco



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!