Get HTML of div element returned by .get with jQuery

时光怂恿深爱的人放手 提交于 2020-01-23 18:27:08

问题


I'm trying to get the HTML of a specific div returned by a .get request (the .get request, returns HTML data with 3 divs with 3 different ids)

Here's my code:

$.get("ajax/learn-more.html", function(data){
    var $response = $(data);
    alert($response.find('#main-images')); // <= prints [Object object]
    alert("Data Loaded: " + data); // <= displaysthe whole html of learn-more.html
    // how can I get the html of a div in learn-more.html with id="main-images" ???
});

EDIT:

The content of learn-more.html:

<div id="something" class="hero-unit span-one-third" style="position: relative;">
    Foo Bar
</div>

<div id="main-images" class="hero-unit span-one-third" style="position: relative;">
    <div id="learn-more-photo" class="span-one-third">
        <img class="thumbnail" src="http://placehold.it/300x180" alt="">
    </div>
</div>

<div id="learn-more">
:D
</div>

回答1:


$response.find('#main-images') will return an empty jQuery object. None of the selected elements has a descendant with ID main-images. Instead, one of the selected elements is the one you are looking for.

To get the a reference to the div use .filter() [docs] instead :

$response.filter('#main-images');

If you want to get the HTML, append the content to an empty div first and remove the unwanted elements:

var container = $('<div />').html(data);
container.children().not('#main-images').remove();
var html = container.html();

or use a outerHTML plugin:

var html = $response.filter('#main-images').outerHTML();



回答2:


$(data) returns an array of elements and not an ordinary jQuery object. $(data)[1] contains your #main-images element.

As Felix Kling answered, you can use filter instead of find.

$(data).filter('#main-images').html();


来源:https://stackoverflow.com/questions/8818603/get-html-of-div-element-returned-by-get-with-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!