jQuery load() Method

The jQuery load() method allows HTML or text content to be loaded from a server and added into a DOM element.

Syntax:
$.load(url,[data],[callback]);

Parameters Description:

  • url: request url from which you want to retrieve the content
  • data: JSON data to be sent with request to the server.
  • callback: function to be executed when request succeeds

The following example shows how to load html content from the server and add it to div element.

Example: Load HTML Content
$('#msgDiv').load('/demo.html');
    
<div id="msgDiv"></div>

In the above example, we have specified html file to load from the server and add its content to the div element.

Note : If no element is matched by the selector then Ajax request will not be sent.

The load() method allows us to specify a portion of the response document to be inserted into DOM element. This can be achieved using url parameter, by specifying selector with url separated by one or multiple space characters as shown in the following example.

Example: jQuery load() Method
$('#msgDiv').load('/demo.html #myHtmlContent');

<div id="msgDiv"></div>

In the above example, content of the element whose id is myHtmlContent, will be added into msgDiv element. The following is a demo.html.

demo.html content:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <h1>This is demo html page.</h1>
    <div id="myHtmlContent">This is my html content.</div>
</body>
</html>

The load() method also allows us to specify data to be sent to the server and fetch the data.

Example: Set Data in load()
$('#msgDiv').load('getData', // url 
                  { name: 'bill' },    // data 
                  function(data, status, jqXGR) {  // callback function 
                            alert('data loaded')
                    });

<div id="msgDiv"></div>

In the above example, first parameter is a url from which we want to fetch the resources. The second parameter is data to be sent to the server. The third parameter is a callback function to execute when request succeeds.

Points to Remember :
  1. $.load() method allows HTML or text content to be loaded from a server and added into a DOM element.
  2. Syntax:
    $.post(url,[data],[callback])
  3. Specify selector with url to specify a portion of the response document to be inserted into DOM element. $('#msgDiv').load('/demo.html #myHtmlContent');
Want to check how much you know jQuery?