Search code examples
htmlscript-tagdynamic-html

script tag in java script is not working and dynamic addition too


I'm trying to add a script tag as value of a variable within a script. that is ..

<script>
    $(document).ready(function() {
        var iCnt = 0;
        $('#btAdd').click(function() {
            if (iCnt <= 19) {
                iCnt = iCnt + 1;
                var div = '<div id="node' + iCnt + '" class="item">'+ iCnt +'</div>';
                var jsplmb = '<script> jsPlumb.ready(function() { addPlumb("node'+ iCnt +'") });</script>';
                $('#diagramContainer').after(div);
            }
        });
 });

</script>

which is not working. The close script tag in the variable jsplumb act as the close tag of main script tag.

also the dynamic addition of var div is not adding to

<div id="diagramContainer"> </div>

Solution

  • The script tags are parsed before the code inside them, so the browser doesn't know that you intended the closing script tag to be a string in the code.

    You can break up the closing script tag into separate strings:

    var jsplmb = '<script> jsPlumb.ready(function() { addPlumb("node'+ iCnt +'") });</scr' + 'ipt>';