Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy / clone script tag with jquery

I have a <script> tag with content within a <div>element. Now I need to copy / clone the content, store it in a variable and append it later.

Strangely when I append the variable content, I just get the outer <div>.

Any idea what I'm doing wrong? We are using jQuery 1.8.2.

Here is my code:

html content:

<div id="payl">
    <div class="toolTipHandler">
        <script type="text/javascript">
            var xxx_title = "<h4>title</h4>";
            var xxx_text = "<p>bla bla</p>";
        </script>
    </div>
</div>

script.js content:

var toolTipHandler = jQuery('#payl .toolTipHandler').clone(true);
document.getElementById('payl').innerHTML = '';
jQuery('#payl').append(toolTipHandler);

Result:

<div class="toolTipHandler"></div>
like image 386
Sebsemillia Avatar asked Oct 30 '22 07:10

Sebsemillia


1 Answers

According to

https://jquery.com/upgrade-guide/1.9/

Prior to 1.9, any HTML-accepting method (e.g., $(), .append(), or .wrap()) executed any scripts in the HTML and removed them from the document to prevent them from being executed again

So the problem is the .append() is removing the script

A workaround might be to just use plain html to "clone and append" eg. Say you have another div

<div id='payl2'>....</div>

Just copy the innerhtml

document.getElementById('payl2').innerHTML=document.getElementById('payl2').innerHTML+document.getElementById('payl').innerHTML;

Result would be:

<div id='payl2'>....

<div class="toolTipHandler">
    <script type="text/javascript">
        var xxx_title = "<h4>title</h4>";
        var xxx_text = "<p>bla bla</p>";
    </script>
</div>

</div>
like image 178
Khelmo Avatar answered Nov 08 '22 09:11

Khelmo