How do I load html into a variable with jquery

While creating a new element is one option, you could also clone any element. This copies all the attributes and the values of the old Node, as it says, 'exact clone'.

In case you want only a particular section of the html to be copied, this also provides the flexibility to fill all the contents within the particular element hierarchy (i.e., with all the children included) from the fetched page.

For instance, if the hierarchy is -

<div id='mydiv'>
    <div>
        <span>
        ...</span>
    </div>
</div>

//...

var oldElement = document.getElementById('mydiv');
var newElement = oldElement.cloneNode(true);

/* #selector selects only that particular section & the '> *' enables to copy all of the child nodes under the parent #selector
Replace URL with the required value
function specification is optional... */

jQuery(newElement).load(URL+'#selector > *'[,function(response, status, xhr){}]);

//...

Now you can programatically process the variable newElement as you want (using native javascript as well, since it is a native element).


You could also create an element in memory and use load() on it:

var $div = $('<div>');

$div.load('index.php #somediv', function(){
    // now $(this) contains #somediv
});

The advantage is that you can specify which part of index.php you want to load by using a selector ( #somediv )


$.get("http://www.mypage.com", function( my_var ) {
    // my_var contains whatever that request returned
});

Underneath, jQuery will launch an ajax request which fires to the given URL. It also tries to intelligently guess which data is going to be received (if it's valid html you don't need to specify). If you need to get another data type just pass that in as last argument, for instance

$.get("http://www.mypage.com", function( my_var ) {
    // my_var contains whatever that request returned
}, 'html');  // or 'text', 'xml', 'more'

Reference: http://api.jquery.com/jQuery.get/