Sunday, February 12, 2012

How to .load() just a specific div from a page into a a target div, not the whole page


I have the following script that loads a page into a div and not just the targeted div. This is most evident when going back to my index and my header and footer are jammed into the <div id="contentspace"></div> .



I read on here somewhere that the div needs to be placed in it's own page prior to being displayed. Not sure which method would do that. Is this possible without hashtags Thanks for your help




<script type="text/javascript">
$(function() {
$('#header a').click(function() {
$('#contentspace').empty();
$("#contentspace").load(this.href, function(response){
console.log($('#content', response).html())
event.preventDefault();
});
});
});
</script>

2 comments:

  1. The method .load() can load page fragment, simply by specifying a valid jquery selector next to the url.

    $('myelement').load('page.html #content', function() {
    ...
    });


    Note that when loading page fragments, jquery will remove any SCRIPT element it might contain.

    In you example, you would do:

    $("#contentspace").load(this.href + ' #content', function(response){
    ...
    });

    ReplyDelete
  2. Did you read the documentation at all? Take a look at the section titled Loading page fragments in the jQuery API for .load(). Essentially you just pass a selector along with the URL of the page to load as the first argument of the method.

    ReplyDelete