views:

48

answers:

4

I would like to .get a page and then use jquery to find elements such as links. How do i make $('#blah') search the get data instead of the page?

+2  A: 

You should be able to create a dom element from the returned HTML without actually adding it to the document, and then search through that using the jQuery methods:

jQuery.get('/my_url/', function(html_data) {
  // If your html_data isn't already wrapped with an HTML object, you may
  // need to wrap it like so:
  //
  // var jQueryObject = $("<div>" + html_data + "</div>");
  var jQueryObject = $(html_data);
  jQueryObject.find("a.link_class");

  // Or, as stated by gregmac below, you could just do the following:
  $("a.link_class", html_data);

  // or, if wrapping is required:
  $("a.link_class", "<div>" + html_data + "<div>");
});
Topher Fangio
Pretty sure you can just do `$('a.link_class', html_data)` in the function body. The second parameter to `$()` specifies the context or data to search. You can actually pass it an XML document, for example, and then pull out elements/data.
gregmac
@gregmac - Interesting. I did read that on the jQuery API page, but I didn't test it. Thanks for the info :-)
Topher Fangio
@gregmac - Just tested it, you are absolutely right; however, there has to be some element wrapping the `html_data` (such as a `<div>`) or jQuery can't parse it properly.
Topher Fangio
A: 

I'm pretty sure you'll be limited to only getting links from a local server/page too.

// create blank array
var links = new Array();

// where should we $.get
var url = '/menus';

$.get(url, function(data) {

    // get anchors from the url
    links = $(data).find('a');

    // loop through all of them
    for(i=0; i<links.length; i++)
    {
        // do something (may alert a lot of links... be prepared)
        alert($(links[i]).attr('href'));
    }
});
Craig
A: 

you can simply do this:

$('#result').load('ajax/test.html #container');

only the content of #container will be shown.

pixeline
+1  A: 

For finding links or a specific element like your example, you can do this:

$.get('test.html', function(data) {
   var links = $('a', data); //Use the response as the context to search in
   var blah = $('#blah', data);
});
Nick Craver