0

I'm making a greasemonkey userscript that is supposed to preload certain data (actually, xkcd comic strips) and display them when link is clicked.

My task mostly consists of retrieving data from DOM fetched by ajax and assigning the values to DOM the user is viewing. This is one particular case I find jQuery incredibly helpful. But jQuery operates on window.document.

I load and parse document like this:

   xhr.onload = function() {
       var doc = document.implementation.createDocument(
         'http://www.w3.org/1999/xhtml',
         'html',
         document.doctype
       );
       doc.documentElement.innerHTML = this.responseText;
   }

And I need to perform jQuery selectors on doc, so that I can retrieve the site data (such as comic title).

Once more, the question: How to perform jQuery selectors on custom document object?

3
  • 3
    Does $(doc) not work? Commented Dec 10, 2014 at 12:58
  • 1
    use $(doc).find(selector) Commented Dec 10, 2014 at 12:59
  • $(doc) will do the job Commented Dec 10, 2014 at 12:59

2 Answers 2

3

You can simply use $(doc) and jQuery's traversal methods:

var $doc = $(doc);

var comicContainer = $doc.find('#comics'); // for example
Sign up to request clarification or add additional context in comments.

Comments

0

To add, for example, click events to custom loaded items, use this:

$(body).on( 'click', 'YOUR_DYNAMIC_SELECTOR', function(){ DO_ALL_THIS } )

3 Comments

What is the body variable here?
It is just the html body. It doesn't have to be the body, ultimately put in there the selector of an element that contains all of your dynamically loaded html.
The click will fire on click of the item selected in the $(), but will look for YOUR_DYNAMIC_SELECTOR which is relevant to the click

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.