Cole Gillespie Cole Gillespie - 1 year ago 89
Javascript Question

how can i get dom elements from html using jQuery's ajax method?

I have encountered a unique problem. I am doing a simple ajax call using jQuery to get the contents of an html file.

url: "foo.html",
dataType: "html",
success: function(data){

foo.html is a simple html file with a main div called #mainContainer. All I want to do is get all of the contents from the mainContainer and store them in a var so i can add them to another div somewhere in my page.

Here's index.html (the file that is making the call).

Here's foo.html (the file i am trying to call and parse).

Answer Source

The jQuery ".load()" API does exactly what you're asking for:

$('#the_target_div').load("foo.html #mainContent", function() {
  // stuff to do when content is ready

You simply add a selector string after the URL, separated by a space.

One thing to note: if the loaded page has any important JavaScript in it (in <script> tags), when you load the page that way the scripts will not be run. If you need that behavior, then you either have to pull out the content yourself (which is a minor mess) or else have your server do the work and respond with only the fragment you need.

A completely different approach would be to load your page into a hidden <iframe> and then dive into that DOM to find what you want. It could then be copied into the main page.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download