Skip to content

Instantly share code, notes, and snippets.

@bojanbjelic
Last active June 18, 2018 10:58
Show Gist options
  • Select an option

  • Save bojanbjelic/4556776 to your computer and use it in GitHub Desktop.

Select an option

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

mdumic commented Jan 19, 2013

Copy link
Copy Markdown

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
Copy Markdown
Author

Good stuff - thanks for the improvements!

@notrealdev

Copy link
Copy Markdown

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