Similar questions have been asked. I’m looking to clarify the best solution for a specific scenario.
I want to move all the innerHTML to another element. I have:
<div class='mydiv'>
Any HTML could be here. <span></span><div></div> etc..
</div>
And want to append/prepend/insertAfter/whatever to this div:
<div class='myotherdiv'>
Any HTML could be here as well. <span></span><div></div> etc..
</div>
Is innerHTML += and the like the only viable solution? Or is there some way to move the whole node list from the first div and append it to the second div? I COULD grab every node individually, loop and append them in order to the second div – I do not want to do that, for performance reasons. I’m looking for some voodoo magics here, old browser need not apply, and no libraries, please.
Probably the most efficient way is to use a
DocumentFragment:If you really wanted to avoid the
whileloop then you could use theextractContents()method of a DOM Range (note: not supported in IE < 9). Theoretically, it could be more efficient than the previous approach since it reduces the number of DOM calls made by script, but I haven’t benchmarked it.