25

You will see from this code that it loads the content URL from the hash tag. Is there anyway to load only a single div element from that external page.

$(function() {
    if(location.hash) $("#content_inload").load(location.hash.substring(1)); 
    $("#nav a").click(function() {
            $("#content_inload").load(this.hash.substring(1));
    });
});

so something like after .substring(#inload_content(1))

but that does not work.

Thanks

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Walrus
  • 19,801
  • 35
  • 121
  • 199
  • Please note that the div in the other page may not be created with JavaScript. –  Nov 04 '10 at 22:09

2 Answers2

57

You just need to add a jquery selector after the url.

See: http://api.jquery.com/load/

Example straight from the API:

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

So what that does is it loads the #container element from the specified url.

Radu
  • 8,561
  • 8
  • 55
  • 91
  • OK thanks very much however what do we do in this situation whereby rather than have an exacting URL we have this.hash.substring . Obviously it would not work to have this.hash.substring '#container' so how would one do it $("#content_inload").load(this.hash.substring(1)); – Walrus Nov 05 '10 at 11:31
  • @Robin Knight $("#content_inload").load('this.hash.substring(1) #container'); should work – Radu Nov 05 '10 at 13:27
  • Unfortunately not. Because the this.hash.substring is not incased in parenthesis it cannot function. It would be something along the lines of this.hash.substring(1) '#container' but that does not work so presumably something else is needed. Any Ideas? – Walrus Nov 05 '10 at 13:49
  • @Robin Knight try: this.hash.substring(1) + ' #container' – Radu Nov 05 '10 at 16:55
  • Marvellous. The load script however is not loading the XFBML Like Button. Any idea how to get that working too. Sample at http://www.divethegap.com/update/events/ – Walrus Nov 05 '10 at 21:42
  • @Robin Knight I would make a new question for that, make sure you're specific about what resource isn't loading - I couldn't tell just by looking at the code. – Radu Nov 05 '10 at 23:15
  • is there an approach on Vanilla Javascript? – Matias Seguel Jan 31 '20 at 19:28
11

Yes, see "Loading Page Fragments" on http://api.jquery.com/load/.

In short, you add the selector after the URL. For example:

$('#result').load('ajax/test.html #container');
Zack Bloom
  • 8,309
  • 2
  • 20
  • 27