CodingMageSheen
CodingMageSheen

Reputation: 154

Ajax Request - Grab/Load only Div Id

I want to do an Ajax request that grabs only the ID from a page without loading the entire page, is that possible? This is how I'm currently doing it now. I can get the information from the ID on the page, however it's loading the entire page including all images from the site thus slowing down the process.

$.ajax({
       type: "GET",
       url: randomUrl,
       success: function (data) {
           $data.find("#wantedID").html(),
       }
});

Upvotes: 1

Views: 1288

Answers (1)

castletheperson
castletheperson

Reputation: 33466

If you need to load the HTML directly into an element in the DOM, use .load() to make the AJAX request, so that you can specify a selector for what part of the document you want to load.

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.

$( "#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.

In your case you would use:

$("#destination").load(randomUrl + " #wantedID");

If you need to further manipulate the response, load the response into a hidden DOM element, and then retrieve the HTML from there.

Upvotes: 2

Related Questions