首页 > 解决方案 > Remove a div from .get() request

问题描述

How do I remove a div (lets name it div_2) from div_1 which is been loaded via .get() with this code:

    $.get('mysite.html', {}, function(data) {
       var $response = $('<div />').html(data);
       var $div_1 = $response.find('#div_1');
       $('#container-div').append($div_1);      
    },'html');

I need it to be done only with this code, so no .load() and etc.

I tried this:

    $.get('mysite.html', {}, function(data) {
       var $response = $('<div />').html(data);
       var $div_1 = $response.find('#div_1');
       $('#container-div').append($div_1, function() {
        $('#div_2').remove();
    });       
    },'html');

Didn't work. Can someone help me with this?

标签: javascriptjqueryget

解决方案


You've parsed the data and stored the parsed result in $response. Just as you've found div_1 in it with find, you can do the same to find div_2 in it — and then remove it. Either initially after parsing, or after finding #div_1:

$.get('mysite.html', {}, function(data) {
   var $response = $('<div />').html(data);
   var $div_1 = $response.find('#div_1');
   $div_1.find("#div_2").remove(); // <====================
   $('#container-div').append($div_1);      
},'html');

推荐阅读