template tag innerHTML breaks script tags

766 views Asked by At

I'm trying to run a string of HTML through the HTML parser which contains <tr> elements. Using the normal HTML parser the <tr> elements would disappear because you can't create them outside of a <table> element. So I tried to use a <template> element and use innerHTML, since template tags don't have the same restrictions and can create the <tr> elements just fine. This worked pretty well and I was able to create the elements just fine.

var html = '<tr><td>foo</td></tr><tr><td>bar</td></tr>';
var template = document.createElement('template');
template.innerHTML = html;
document.body.appendChild(template.content);

However, later on I tried to do the same thing using <script> tags instead of table rows, but when the template is added to the body, the script tag doesn't run.

var html = '<script>alert("hello");</script>';
var template = document.createElement('template');
template.innerHTML = html;
document.body.appendChild(template.content);  // doesn't execute the script

But if I were able to create a script tag and append it to the template it would work.

var template = document.createElement('template');
var script = document.createElement('script');
script.textContent = 'alert("hello");';
template.content.appendChild(script);
document.body.appendChild(template.content);  // does execute the script

Does anyone know why using innerHTML breaks script tags for templates (style tags also work fine using this method)?

0

There are 0 answers