Skip to content

Instantly share code, notes, and snippets.

@bojanbjelic
Last active June 18, 2018 10:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bojanbjelic/4556776 to your computer and use it in GitHub Desktop.
Save bojanbjelic/4556776 to your computer and use it in GitHub Desktop.
Selecting Elements Returned From Jquery Ajax Response Strings
$(function () {
$.get('contentUrl', function (response) {
var source = $('<div>' + response + '</div>');
$('#target').empty().append(
$('<div/>')
.append(response)
.find('#selectorInResult');
);
});
});
@mdumic
Copy link

mdumic commented Jan 19, 2013

This avoids parsing HTML twice (once via $(result) and then when inserting it back via .html()):

$('#target')
    .empty()
    .append(
        $('<div/>')
            .append(response)
            .find('<selector>')
    );

Also, if you receive bad HTML and try to wrap it in div by concatenation you could end up with fragment with more than one element at the top level. Your find will then miss all topmost siblings. Previous approach ensures the single root div to search from.

If you are sure your match is at top level this will suffice (no need for wrapping the div around the result):
$(response).filter('<selector>')

@bojanbjelic
Copy link
Author

Good stuff - thanks for the improvements!

@notrealdev
Copy link

Hi, selecting elements returned from Vanilla JS Ajax response strings ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment