This is driving me crazy…
What I am trying to do is update a portion of a webpage, and for reasons not worth explaining, the request is asking for a whole new HTML page (including its head) and then pulling out only the HTML that was contained within a specified element (identified by an ID).
Originally, I had the following JavaScript code that would run whenever an AJAX request for new HTML completed:
var $newContent = $(newHtmlContent);
loadingElement.innerHTML = $("#" + loadingElementId, $newContent).html();
This was great until I had a bit of HTML that was loaded that, contained within the specified element, included some scripts that needed to be run, so I changed it to this:
var $newContent = $(newHtmlContent);
$(loadingElement).html($("#" + loadingElementId, $newContent).html());
I have read that jQuery will evaluate any scripts with the HTML string argument of the html() function – however, it seems the issue is that the scripts are stripped before this call.
Having had a look through firebug the following seems to be happening:
$(newHtmlContent) // includes all 'script' elements
$("#" + loadingElementId, $newContent) // has no scripts
$("script", $newContent) // empty jQuery object
Does anyone have any suggestions?
Thanks in advance.
Did a quick test (fiddle), given the following markup as string:
jQuery will produce an object like
[0]will contain all of the html in#rootexcept for the script, the scripts are separated into their own objects. This seems to be true for all scripts within the markup.So you could do something like this to run the script: