Use Ajax() function in Jquery to load PART of an external page into div

user196986 picture user196986 · Oct 27, 2009 · Viewed 26.5k times · Source

I'm trying to load a DIV element from an external page into my current page using the Ajax/jQuery.ajax function. While I have successfully been able to load an entire external page, I can't seem to load just the DIV element.

Here's my code:

$("a").click(function() {
  /* grabs URL from HREF attribute then adds an  */
  /* ID from the DIV I want to grab data from    */
  var myUrl = $(this).attr("href") + "#external-div";
  $.ajax( {
  url: myUrl,
  success: function(html) {
    /* loads external content into current div element */
    $("#current-div").append(html);
    }
  });
  return false;
});

It grabs the HREF attribute without any trouble, but won't append "#external-div" to the URL. Any ideas?

Thanks much!

~Jared Crossley

Answer

Quintin Robinson picture Quintin Robinson · Oct 27, 2009

If you wanted to just return that div you could use the load method of jQuery to simply load the content returned into your #current-div ala

$("a").click(function() {
  /* grabs URL from HREF attribute then adds an  */
  /* ID from the DIV I want to grab data from    */
  var myUrl = $(this).attr("href") + " #external-div";
  $("#current-div").load(myUrl);
  return false;
});

Take a look at the jQuery Ajax/load documentation