0

I remember using a plugin in the past where I could use AJax to load a page and update only part of the DOM. The AJax request returns the entire HTML page, but only a small portion of it replaces part of the currently loaded DOM.

For example, SO can use this function to fetch http://stackoverflow.com and only update #content. SO would make an AJax request to fetch http://stackoverflow.com, fetch #content from the returned string, and update #content of the DOM.

Sorry if my question is confusing. How would I do this without a plugin?

1
  • Your question is not very clear, or I'm having a problem understanding it. "How would I do this without a plugin?" What does "this" refer to? What you were referring to in your example is the $.fn.load method. Commented Apr 20, 2012 at 21:49

2 Answers 2

3

The .load() function is designed to do this. Just include a selector for an element along with the URL, like so:

$('#content').load('http://stackoverflow.com #content', optionalCallbackFunction);

That will replace the content of the element with ID content on the current page, with the contents of the element with ID content on the page returned by an AJAX request to http://stackoverflow.com, then run the function called optionalCallbackFunction. Assuming, of course, that the request was successful.

Sign up to request clarification or add additional context in comments.

4 Comments

So $('some element to replace the content of') is probably $('#content').
yes - ajax.load is your main option here. Refer to this link full the details: api.jquery.com/load. It includes the full description of how to load portion of the page as highlighted by Anthony above.
The only thing I don't like about the .load() method is that it actually loads the whole page first and then it gets the content from the specific section with id="#content" in this case. It is pretty much like having a hidden inline content.
@JFK I see your point, though I can't think of any way to avoid loading the entire page in a purely Javascript solution.
0

Without the AJAX, you can parse a raw string like this:

var str = "<div><h1>Page Title</h1><div id='content'>This is new.</div></div>";
var text = $("#content",$(str)).html();
$('#content').html(text);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.