tags:

views:

1683

answers:

5

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  A: 

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.

nakajima
+1  A: 

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.

Brian Fisher
+5  A: 
// Finds all div elements within an XML document from an AJAX response.
$("div", xml.responseXML);
Beau Simensen
I voted this one up, though on second thought, I think that calling `find` explicitly is more readable, especially to someone who's less familiar with the framework.
nakajima
+2  A: 

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');
stuartloxton
A: 

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

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