Skip to content

Instantly share code, notes, and snippets.

@g-rodigy
Last active October 23, 2019 21:10
Show Gist options
  • Save g-rodigy/41c76e72ed394c0f458eef61db05e6cf to your computer and use it in GitHub Desktop.
Save g-rodigy/41c76e72ed394c0f458eef61db05e6cf to your computer and use it in GitHub Desktop.
Insert html and attach js code
function html(text, dest) {
var el = document.createElement('div'); // we can't do it without wrap
el.insertAdjacentHTML('afterbegin', text);
var scripts = el.querySelectorAll('script');
for (var i = 0; i < scripts.length; i++) {
var scriptEl = document.createElement('script');
scriptEl.innerHTML = scripts[i].innerHTML;
for (var j = 0; j < scripts[i].attributes.length; j++)
scriptEl.setAttribute(scripts[i].attributes[j].nodeName, scripts[i].attributes[j].nodeValue)
scripts[i].replaceWith(scriptEl);
}
if (typeof dest == 'string')
dest = document.querySelector(dest);
dest.appendChild(el);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment