Friday, February 12, 2010

How to access an arbitrary Document from jQuery.

I've had great difficulty finding this on the web so here it is, and as usual its super simple but that didn't stop me taking hours to find it.

jQuery uses the notation $('div#test') as shorthand to access node 'thing' in the current Document.
If you are processing an XML document you read from an external source and want to just grab a bit of it and use jQuery, then you use this (assuming xhr is the XmlHttpRequest):

var xmlDoc = $(xhr.responseXML); 
var myValue = xmlDoc.find('towel#colour').attr("blue")


So once again, if you want to use selectors on documents other than the current DOM Document, use find().

View find() docs which, ironically, are hard to find on jQuery.com
There was an error in this gadget