0

I am trying to use ajax to grab an element with a specific class from another file using jQuery, parse the html to get some data out of it and put it into an object, then display the data in different markup than the original html within #content, an element on the main page..

When using load(), I can target a specific class:

$("#content").load("article.html .cover", function(){
    console.log("load() success");
});

This works, but I don't want the html from article.html to be put into #content, so I tried using ajax() so that I can manipulate the html before displaying it in the callback:

$.ajax({
    url: "article.html .cover"
}).done(function(){
console.log("ajax() success");
});

but this results in a 404 error. get() results are the same as ajax().

$.get("article.html .cover", function(){
    console.log("get() success");
});

How can I use get() to target this specific element?

Alex
  • 335
  • 1
  • 4
  • 15

1 Answers1

4

You can try this:

$.get("article.html", function(html){
   var cover = $(html).find('.cover');
});

There's no magic in $.get as it seems to be in $.load to find a specific element in the page. You can get any file type with $.get, and it would not make sense to add a selector when fetching a json file, for example.

Edit

If you care about performance, apparently $.get uses cache by default (link).

You can (should?) also return only what is needed, if your server-side code allows it. Maybe requesting articlecover.html insted of article.html.

Community
  • 1
  • 1
Johnny5
  • 6,664
  • 3
  • 45
  • 78
  • just outa curiosity, why would `$.get("article.html .cover")` return a 404? – Phil Jan 23 '14 at 14:37
  • Because it is not a valid url. – Johnny5 Jan 23 '14 at 14:37
  • oh, okay, I guess that is looking for a URL and not a query string, lol thank you – Phil Jan 23 '14 at 14:38
  • That's it, $.get does not target specifically html files, like $.load. – Johnny5 Jan 23 '14 at 14:41
  • This works, but I was hoping to find a way of doing this without requesting the entire page. I'm going to be looping through lots of files that may include lots of images and wanted to keep the amount of excess to a minimum. Will this make a negligible difference to load time? – Alex Jan 23 '14 at 15:54
  • I'm pretty sure that `$.load` is also requesting the whole page. I mean, jQuery will not filter your html _on the server side_. If you want to reduce traffic, think about returning just the part you need. That said, I _think_ that `$.get` uses caching by default. – Johnny5 Jan 23 '14 at 16:08
  • You can check the requests in your browser by hitting F12 and going to the _Network_ tab in firefox or chrome. – Johnny5 Jan 23 '14 at 16:09