Quantcast
Channel: Replace element contents with document fragment javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 4

Answer by Thomas Jones for Replace element contents with document fragment javascript

$
0
0

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/


Viewing all articles
Browse latest Browse all 4

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>