Search code examples
jqueryclone

How to clone <script> tags with jQuery


I have the following code (simplified to see the logic behind):

<div id="alfa">Text
    <script>
        $("#alfa").click(function() {
            alert($(this).attr("id"));
        });
    </script>
</div>
<script>
    var clone = $("#alfa").clone().attr("id",$("#alfa").attr("id")+"_1");
    $("#alfa").after(clone);
</script>

I need to see "alfa_1" when I click in the cloned Text, but nothing happens.

When I use clone(true,true) that works, but I don't see the code of the cloned div in Firebug to see what really happens.

Also I don't know why clicking the original div the alert is triggered twice.

Thanks.


Solution

  • I need to see "alfa_1" when I click in the cloned Text, but nothing happens.

    Doing DOM or innerHTML manipulations on <script> elements is inconsistent in browsers and doesn't really make any sense in terms of the JavaScript execution cycle. Avoid it in all cases.

    If you want to copy DOM elements together with their jQuery event handlers, use clone(true):

    <div id="alfa">Text</div>
    
    <script type="text/javascript">
        $('#alfa').click(function() {
            alert(this.id);
        });
        var clone= $('#alfa').clone(true);
        clone[0].id+= '_1'; // sorry, I couldn't bring myself to do this the jQuery way
        $('#alfa').after(clone);
    </script>