Use Jquery Selectors on $.AJAX loaded HTML?

Viewed 79147

I have

$.ajax({
  url: identity,
  success: function(data) { ProcessIdentityServer(data) }
});

When 'data' is returned, is there a way to run selectors against it without adding it into the DOM. So for example, how can I get all the href values of any LINK tags contained in the HTML held in 'data' without adding it to the DOM first? Seems a shame to have to add it into the DOM if all I want to do is extract some stuff into an array. Anyone got any ideas?

9 Answers

One note I will add which is from a similar problem on here is that if your AJAX returns the following:

<div class="test">Hello</div>
<div class="one">World</div>

The following jQuery Won't work:

$(data).find('div.test');

as the divs are top level elements and data isn't an element but a string, to make it work you need to use .filter

$(data).filter('div.test');
// Finds all div elements within an XML document from an AJAX response.
$("div", xml.responseXML);

Presuming that data is a string of HTML, you can do this:

$(data).find('a');

That will return the links without adding the data to the DOM.

Sure you can use the $(data) function, one of the core jquery functions, to turn the returned html into DOM elements. Check out the docs online.

You can also use context now (don't know when this was introduced):

$.get('some/url', '',
    function (data) {
        $("#domelement", data);
    }
);
Related