Finding an element by ID in an AJAX Response with jQuery

I got a full 'html' page returned by ajax, but I only need partial of its content, which wrapped by a div and also I need to execute the script inside the 'html' page.

 $.ajax ({
  type: "POST",
  url : "contact.php",
  data: $("#formContactUs").serialize(),
  success: function(msg){
    console.log($(msg)); // this would returned as an array
    console.log(msg);    // return whole html page as string '<html><body>...</body></html>'
    $('#id').html($(content).closest('.target-class'));
    $('#id').append($(content).closest('script')[0]);  // append and execute first script found, when there is more than one script.
  }
});

@kevin answer gave hints to why find() is not working as expected, as it only select its descendant but not the first element under consideration. Besides using filter, $.closest() also works if current element is what you are looking for. Well, probably this post quite similar to @Kevin's answer, it's just to suggest another alternative answer and gave more details which hopefully make thing clearer.


Notice how all of the elements are on the same level? You need to use .filter() to narrow down the current selection to a single element in that selection, .find() will instead look at the descendants of the current selection.

var success =  $($.parseHTML(response)).filter("#success"); 
console.log(success); // div#success

try the following if the above answers didn't work

var successHtml = $($.parseHTML(response)).find("#success").html();