最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - how can i get dom elements from html using jQuery's ajax method? - Stack Overflow

programmeradmin3浏览0评论

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

$.ajax({
  url: "foo.html",
  dataType: "html",
  success: function(data){
    console.log(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).

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

$.ajax({
  url: "foo.html",
  dataType: "html",
  success: function(data){
    console.log(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).

Share Improve this question edited Nov 30, 2016 at 5:21 Nikhil 3,7119 gold badges34 silver badges43 bronze badges asked Jun 18, 2011 at 15:15 Cole GillespieCole Gillespie 31 silver badge2 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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 pletely 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.

var mainContainerInnerHtml = $(data).find("#mainContainer).html();

you do not need get the dom elements. you can use query replaceWith function to replace.

just like this:

$("#data").replaceWith($("#data",ajaxReturnHtml)).serialize();

it works to me.

发布评论

评论列表(0)

  1. 暂无评论