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?

1
  • Fetch inside the done() callback where you have access to the HTML Commented Jan 23, 2014 at 14:35

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

just outa curiosity, why would $.get("article.html .cover") return a 404?
Because it is not a valid url.
oh, okay, I guess that is looking for a URL and not a query string, lol thank you
That's it, $.get does not target specifically html files, like $.load.
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?
|

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.