Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically adding div element from html encoded string containing Div and Script markup

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 = "&lt;div id=&#39;testDiv&#39;&gt;\n &lt;script src=&quot;http://d3js.org/d3.v3.min.js&quot;&gt;&lt;/script&gt;\n &lt;script&gt;\n d3.select(&quot;#testDiv&quot;) \n .data([4, 8, 15, 16, 23, 42])\n .enter().append(&quot;p&quot;)\n .text(function(d) { return &quot;I'm number &quot; + d + &quot;!&quot;;\n });\n &lt;/script&gt;\n &lt;/div&gt;";
        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?

like image 839
mike01010 Avatar asked Dec 25 '22 04:12

mike01010


1 Answers

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])
like image 100
tnt-rox Avatar answered Dec 27 '22 17:12

tnt-rox