1

I have an un-ordered list of links in a navigation like so:

<ul class="main-nav-child">
   <li><a href="/collections/1">collection one</a></li>
   <li><a href="/collections/2">collection two</a></li>
   <li><a href="/collections/3">collection three</a></li>
</ul>

When clicked, I'm loading the html output of each link into a container called .main-content using this snippet:

$('ul.main-nav-child a').bind('click', function(e) {           
  var url = $(this).attr('href');
  $('.main-content').load(url); // load the html response into a DOM element
  e.preventDefault(); // stop the browser from following the link
});

Problem: I want to load just the contents from a certain element from the link, not the entire page. Each page has an element called .main-content and I want to grab that via ajax and display it on the page, again within .main-content

Any guidance on how to filter .load() would be greatly appreciated.

David Alsbright
  • 1,526
  • 1
  • 17
  • 31
  • 1
    What's happening? What errors are shown in the Net tab when you attempt to make the request? Is the AJAX call itself working at all? I expect that your selector is wrong and that it actually wants to be something more like `$(".main-content").load(url + ".main-content");`? – johnkavanagh Nov 29 '13 at 15:22
  • A XMLHttpRequest can only get the entire page, there is no filtering. jQuery's load() has an option to filter out elements from the returned data, or you could just do it yourself with a regaular $.ajax call and filter the returned data. – adeneo Nov 29 '13 at 15:25

1 Answers1

1

You should just be able to reference the selector (docs);

var url = $(this).attr('href');
$(".main-content").load(url + " .main-content");

Note that if .main-content does not exist in your page, it will not bother making the request. Likewise if .main-content does not exist in the target page, nothing will be returned.

Jivings
  • 22,834
  • 6
  • 60
  • 101
  • Thanks, that did it for me, I mis-understood how to filter `.load` now I just need to work out how to update the URL without hashing! – David Alsbright Nov 29 '13 at 16:37
  • @DavidAlsbright Not sure you'll be able to update the URL without a hash without it changing the page! – Jivings Nov 30 '13 at 09:19
  • My thoughts too, I'm looking at this question though: http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page/3354511#3354511. I don't need to support old browsers so that looks promising! – David Alsbright Nov 30 '13 at 11:29