Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from Ajax Response

Let's says I want to load this file by AJAX :

<!-- loadme.html -->

<div class='content'>
    Hello !
    <div class='removeme'>Remove me, please.</div>
</div>

How can I get only the Hello content ? I tried multiples ways to remove the .removeme div, it always failed :

$.ajax({
    url: 'loadme.html',
    success: function(data) {
        var response = $('<div />').html(data);

        // First try :
        var content1 = response.find('.content').html()
        console.log(content1); // Return : Hello ! <div class="removeme">Remove me, please.</div>

        // Second Try :
        var content2 = response.find('.content').remove('.removeme').html()
        console.log(content2); // Return : Hello ! <div class="removeme">Remove me, please.</div>

        // Third Try :
        var content3 = response.find('.content').html();
        console.log($(content3).remove('.removeme').html()); // Return : Remove me, please
    }
});
like image 909
lepix Avatar asked Feb 23 '23 07:02

lepix


1 Answers

Try:

var temp = response.find('.content');
temp.children('.removeme').remove();
var content4 = temp.html();
like image 113
Thomas Li Avatar answered Mar 08 '23 03:03

Thomas Li