i have python app that passes html to page as part of a json payload. what i am trying to do in that page is to decode the html and dynamically add it to the DOM. the html markup is for a Div element with child script elements. this is my code, which prints out the decoded HTML fine, but does not actually execute the script:
<div id="parentDiv">
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script type='text/javascript'>
var child_div = "<div id='testDiv'>\n <script src="http://d3js.org/d3.v3.min.js"></script>\n <script>\n d3.select("#testDiv") \n .data([4, 8, 15, 16, 23, 42])\n .enter().append("p")\n .text(function(d) { return "I'm number " + d + "!";\n });\n </script>\n </div>";
decoded = $('<div />').html(child_div).text();
console.log(decoded);
$("#parentDiv").append(decoded);
</script>
</div>
If however i take that html that is logged in the above code and create a page out of it, it works fine with the script executing as it should. this is what the decoded html looks like and what i am hoping to dynamically add to the parent div:
<div id="parentDiv">
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<div id='testDiv'>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
d3.select("#testDiv")
.data([4, 8, 15, 16, 23, 42])
.enter().append("p")
.text(function(d) { return "I'm number " + d + "!"; });
</script>
</div>
</div>
What am i doing wrong here?
Once you have appended your elements do the DOM they do exist in the DOM however the script has not been initialized.
You can access the script tags with something like this:
function getScriptsAsText() {
var div = document.createElement('div');
var scripts = [];
var scriptNodes = document.getElementsByTagName('script');
for (var i = 0, iLen = scriptNodes.length; i < iLen; i++) {
div.appendChild(scriptNodes[i].cloneNode(true));
scripts.push(div.innerHTML);
div.removeChild(div.firstChild);
}
return scripts;
};
This function will return the scripts in an array. Filter through the array until you find the script you are after and then eval it.
var scripts = getScriptsAsText();
eval(scripts[0])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With