I have a situation where I am getting an HTML response back from our server after an AJAX call. I need to pull a specific element and its children out, and inject it into the DOM.
Currently my AJAX callback looks something like:
var onSuccess = function (rawData) {
var rawData = $(rawData);
var data = rawData.find("#foo");
$("#bar").append(data);
};
This works fine unless #foo
contains <script>
elements. After much poking around, I've determined the problem arises at the very first step:
var rawData = $(rawData);
Passing the HTML into jQuery pulls all the <script>
elements out of their original context and makes them top-level. A subsequent .find("#foo")
fails to bring the previously-nested <script>
elements along for the ride because they've already been moved elsewhere.
Everything works fine when I inject the raw HTML directly into the DOM, but our system is old and will need a lot of massaging before it is able to limit what it returns to just the element of interest, so for now I need to be able to scan the total response and take only what I need. Which includes those <script>
elements.
Any suggestions?
[FOLLOW-UP] Thanks all for the help.
I ended up adapting this solution to my needs, making my AJAX success callback look something like this:
var onSuccess = function (rawData) {
var data = $(rawData);
var scripts = data.filter("script[someAttribute='someValue']");
var elementOfInterest = data.find("#foo"); // scripts above used to live in #foo
$("#target").append(elementOfInterest);
$("body").append(scripts);
};
Note, this requires me to add a special attribute to the nested script elements I want to be carried over.