Bluefire
Bluefire

Reputation: 14109

Traversing an XMLDocument with jQuery selectors

Suppose I have some XML received from an AJAX call. I know how to use selectors on the web page, e.g. if I had <p id="foo"></p> then $("#foo") would select it, but is there a way to get that selector to target my XML instead? So if my XML contained <foo bar="baz"></foo>, then I could select it with $("[bar='baz']").

Upvotes: 1

Views: 196

Answers (1)

raina77ow
raina77ow

Reputation: 106385

Yes, you can; you just need to pass that XMLDocument into jQuery selector (as its context parameter). In fact, you can happily pass a string there:

var xml = '<xml><foo id="foo">bar</foo><foo id="nonfoo">baz</foo></xml>',
 xmlDoc = $.parseXML(xml);

console.log( $('#foo', xmlDoc).text() ); // bar
console.log( $('#foo', xml)   .text() ); // bar

Note that it's (obviously) quite a weird idea to use it like this:

$('#foo', xml).text();
$('#nonfoo', xml).text();
...

... as jQuery will have to reparse that xml string into the XMLDocument object each time.

Upvotes: 4

Related Questions