Skip to content

Instantly share code, notes, and snippets.

@uniqname
Last active August 29, 2015 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save uniqname/ca42af72ecf6aa359bd0 to your computer and use it in GitHub Desktop.
Save uniqname/ca42af72ecf6aa359bd0 to your computer and use it in GitHub Desktop.
Replace an element with a rendered htmlstring
{
"registry": {
"register": "http://bower.ldschurch.org"
}
}
bower install lds-replace-element-with

#Replace an element in the DOM with a rendered HTML string or other node.

var replace = require('replace-element-with'),
    foo = document.querySelector('.foo');

replace(foo, '<p class="bar">I\'m new here!</p>');
{
"name": "replaceElementWith",
"version": "1.0.0",
"authors": [
"Cory Brown <oh.wise.man@gmail.com>"
],
"description": "Simply replace an element in the DOM with a rendered HTML string.",
"main": "replaceElementWith.js",
"moduleType": [
"node"
],
"keywords": [
"replace",
"element",
"DOM"
],
"license": "MIT",
"ignore": [
"**/.*",
"node_modules",
"bower_components",
"test",
"tests"
]
}
var replaceElWith = function (el, htmlstr) {
var render = function (str) {
var div = document.createElement('div'),
frag = document.createDocumentFragment();
div.innerHTML = str;
[].slice.call(div.childNodes).forEach(function (child) {
frag.appendChild(child);
});
return frag;
};
el.parentElement.replaceChild(render(htmlstr), el);
};
module.exports = replaceElWith;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment