jQuery – script tags in the HTML are parsed out by jQuery and not executed

As Pointy pointed out (excuse the pun), jQuery messes with the SCRIPT tags when you pass HTML to $(). It doesn’t remove them though — it simply adds them to the DOM collection produced from your HTML. You can execute the scripts like so:

$.ajax({
    url: 'example.html',
    type: 'GET',
    success: function(data) {

        var dom = $(data); 
        $('#mydiv').html(dom.find('#something').html());
        dom.filter('script').each(function(){
            $.globalEval(this.text || this.textContent || this.innerHTML || '');
        });
    }
});

Leave a Comment