Reputation: 1575
I have two webpages internal.html and external.html
I have the following piece of code in internal.html which loads external.html into div with id "result"
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function autoRefresh_div()
{
$("#result").load("https://abc/external.html");// a function which will load data from other file after x seconds
}
setInterval('autoRefresh_div()', 5000); // refresh div after 5 secs
</script>
I have a div with id "test" in external.html.
How do I load only the div with id "test" of external.html into internal.html's div with id "result" and not the entire page?
Upvotes: 3
Views: 5633
Reputation: 1546
Loading Page Fragments
The .load() method, unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.
We could modify the example above to use only part of the document that is fetched:
$( "#result" ).load( "ajax/test.html #container" );
When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.
jQuery uses the browser's .innerHTML property to parse the retrieved document and insert it into the current document. During this process, browsers often filter elements from the document such as , , or elements. As a result, the elements retrieved by .load() may not be exactly the same as if the document were retrieved directly by the browser.
In your case you'll want to modify your code to:
$("#result").load("https://abc/external.html #test")
Upvotes: 5