Loading html and manipulate it's DOM before inserting it into the document

Loading html and manipulate it's DOM before inserting it into the document

Hi folks, I've some problems loading a complete validated HTML5-File (with <!DOCTYPE html> & <head> & <body>) from a given url, and manipulate it's content (respectively select a specific source-element in it) before inserting it into a target-element in the displayed document.
  1. loadContent = function(url, sourceElement, targetElemet) {
  2.       var ajaxParams = {};
  3.       ajaxParams.url = url;
  4.       ajaxParams.dataType =       "html";
  5.       ajaxParams.success =       function(returnedData) {
  6.                                                       var newDocument = $(returnedData);
  7.                                                       // does not work. no manipulations seems to work
  8.                                                       // even $(newDocument).html() is null.
  9.                                                       // $(newDocument).find("head").remove();
  10.                                                       // clear target-element and insert loaded document
  11.                                                       $(targetElemet).children().remove();
  12.                                                       $(targetElemet).html("");
  13.                                                       $(targetElemet).append(newDocument);
  14.                                                       // this works, but before this, the document is not valid:
  15.                                                       // <head>-element in the middle of the document
  16.                                                       $(targetElemet).find("head").remove();
  17.                                               };
  18.       $.ajax(ajaxParams);
  19. };

$(newDocument).find("head") does not work like I think it should work, and I can not select a specific element in the loaded document, i. e. just the body.

I know the function .load() allows to select specific elements of the loaded document, but i need control over all callbacks, not only on success.

The question is: how can i generate a complete detached DOM-Tree from a loaded url and manipulate it before we insert it into the shown document?