简体   繁体   中英

jQuery - Remove some elements from AJAX response

AJAX response:

<div id="div_1">Some text</div>
<div id="div_2">Some text</div>
<div id="div_3">Some text</div>

Now I need to remove some divse, before the result is shown to users. So lets for example remove div_1 and div_3:

var result = $(ajax_response).find('#div_1, #div_3').remove();

Now we can show it to users:

$('#result_div').html(result);

But it doesn't work - nothing will show up . What am I doing wrong?

EDIT : Working solution, but I don't like, that I have to show the result before a change it:

 $('#result_div').html(ajax_response).find('#div_1, #div_3').remove();

find() only works within the context of an element. The three elements you receive are all siblings, so you can either wrap them in a container on the server side:

<div class="container">
    <div id="div_1">Some text</div>
    <div id="div_2">Some text</div>
    <div id="div_3">Some text</div>
</div>

Or you can do that programmatically in your JS:

var $container = $(ajax_response).wrap('<div />').parent();
$container.find('#div_1, #div_3').remove();
$('#result_div').html($container);

Example fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM