Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
44
rated 0 times [  47] [ 3]  / answers: 1 / hits: 18242  / 12 Years ago, fri, november 9, 2012, 12:00:00

I'm trying to replace all contents of an element with a document fragment:



var frag = document.createDocumentFragment()



The document fragment is being created just fine. No problems there. I add elements to it just fine, no problems there either. I can append it using element.appendChild(frag). That works just fine too.



I'm trying to create a replace method similar to jQuery's HTML. I'm not worried about old-browser compatibility. Is there a magical function to replace all content of an element?



I have tried element.innerHTML = frag.cloneNode(true), (as per every 'replace element content' wiki I could find), that doesn't work. It gives me <div>[object DocumentFragment]</div>.



No libraries, please, not even a jQuery solution.



For clarity, I'm looking for a magic solution, I know how to remove all the existing elements one at a time and then append my fragment.


More From » replace

 Answers
8

Have you tried replaceChild



something like this



element.parentNode.replaceChild(frag, element)


source: https://developer.mozilla.org/en-US/docs/DOM/Node.replaceChild



original jsFiddle: http://jsfiddle.net/tomprogramming/RxFZA/



EDIT: ahh, I didn't see replace contents. Well, just remove them first!



element.innerHTML = ;
element.appendChild(frag);


jsfiddle: http://jsfiddle.net/tomprogramming/RxFZA/1/



note that in the jsfiddle, I only use jquery to hook up the button, the entirety of the click handler is raw javascript.



Edit2: also suggested by pimvdb, but just append the new stuff to a detached element and replace.



var newElement = element.cloneNode();
newElement.innerHTML = ;
newElement.appendChild(frag);
element.parentNode.replaceChild(newElement, element);


http://jsfiddle.net/tomprogramming/RxFZA/3/


[#82081] Thursday, November 8, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
agustindejonm

Total Points: 738
Total Questions: 84
Total Answers: 84

Location: Northern Ireland
Member since Mon, Nov 14, 2022
2 Years ago
agustindejonm questions
Fri, Jun 25, 21, 00:00, 3 Years ago
Fri, Sep 18, 20, 00:00, 4 Years ago
Sat, May 16, 20, 00:00, 4 Years ago
;