Grant
Grant

Reputation: 1337

Finding THIS div or THAT div with AJAX / jQuery

You can load a cross-domain div via AJAX (using this plug-in) like this :

 $.ajax({
   url: 'http://externalurl.com',
   type: 'GET',
   success: function(res) {
     var artwork = $(res.responseText).find('.div1 img');
     $('.mydiv').append(artwork);
   }
 });

Which will return the img tag in div1. But is it possible to search for content on the source site using 2 separate divs?

For example (pseudo code obviously) :

 var artwork = $(res.responseText).find('.div1 img') or .find('.div2 img');

Knowing that div1 and div2 will NEVER be on the same page on the source site. The source site will only ever have either div1 or div 2, but never both.

Upvotes: 2

Views: 69

Answers (1)

arcyqwerty
arcyqwerty

Reputation: 10695

Yes, once you call $(res.responseText) jQuery parses it as a DOM tree.

You can then use regular jQuery selectors (including compound selectors) to "find" the right nodes.

$(res.responseText).find('.div1 img,.div2 img');

Documentation:

Multiple Selector (“selector1, selector2, selectorN”)

Description: Selects the combined results of all the specified selectors. (version added: 1.0j)

Query( "selector1, selector2, selectorN" )

  • selector1: Any valid selector.
  • selector2: Another valid selector.
  • selectorN: As many more valid selectors as you like.

You can specify any number of selectors to combine into a single result. This multiple expression combinator is an efficient way to select disparate elements. The order of the DOM elements in the returned jQuery object may not be identical, as they will be in document order. An alternative to this combinator is the .add() method.

Upvotes: 7

Related Questions