views:

65

answers:

3

I'm trying to retrofit a page to read from XML rather than the DOM, and I'd rather not use $(xml).find('blah') for every single call, and I was wondering if there was a way to point jQuery at xml, rather than the DOM.

For instance, I'd like to be able to navigate my xhtml with the jQuery method as such: $('blah').whatever

Is this possible?

+2  A: 

No, you cannot redirect the global document object to point to an arbitrary DOM document you've created.

jQuery has given you the context argument to the $() function for exactly this purpose, so you should just use that:

$('blah', xmlDoc).whatever()

Or you can store it in a var to reduce repetition if you like, and traverse downwards from there:

var $xml = $(xmlDoc);
$xml.find('blah').foo();
$xml.find('bloh').bar();
Crescent Fresh
Using this method, is there any way I can modify the XML document on the fly? $('blah', xmlDoc) works, but something like $('blah', xmlDoc).removeClass( 'hidden' ) doesn't seem to work.
Stefan Kendall
+1  A: 

It's a bit dodgy but you could override the $ function:

var old$ = $;
var xml = ...;

$ = function(arg)
{
    return old$(arg, xml);
}

I think that should work... maybe...

Greg
There you go thinking outside the box again :) Nice.
Crescent Fresh
+1  A: 

If you're using a method like jQuery.ajax() or jQuery.get() to retrieve the DOM from another page, just change/set the return type from "json" to "xml".

http://docs.jquery.com/Ajax/jQuery.ajax#options (scroll down to "dataType")

James Jones