简体   繁体   中英

jQuery .remove() removes all my children from the container not just one

Im working on building out a full page transition using aJax calls. I want to remove content from the DOM when I load in a new page. Some reason .remove() is removing all the children from the parent container even though Im adding a unique class or ID on it. I've tried several ways of targeting the element I want to remove but it keeps doing the same thing. remove() should only be removing one element, that is the element with the class name 'remove-from-dom' When I use addClass it targets the element correctly.

                    $(response).prependTo('.swap-content');

                    var slideWidth = $('.swap-content').width();
                    $('.ajax-load-in-remove').animate({
                        left: + slideWidth
                    }, 1000, function () {
                        $('.ajax-load-in-remove').css('left', '').removeClass('hide-me');
                        $('.ajax-load-in-remove').last().addClass('remove-from-dom');
                        $('.remove-from-dom').remove();

                    });

my container looks like this

    <div class="parent">
        <div class="child">
        <div>
        <div class="child remove-from-dom">
       <div>
    </div>

.remove() should only be removing the last child in the container but its removing both children. I only have 2 children. I have tried using IDs and have used .last-child and .last()

If you want to remove the last one .ajax-load-in-remove , use

$('.ajax-load-in-remove').last().remove();

You don't need to add remove-from-dom class to this element, it was just a step more to make an action.

The problem is that you are doing the removing inside the callback when the animation ends.

But you are running the animation on many elements $('.ajax-load-in-remove').animate , so the callback is fired for each animation ending. And each callback is removing the currently last element.

You can use the .promise which resolves when all animations have completed.

$('.ajax-load-in-remove')
  .animate({
    left: +slideWidth
  }, 1000)
  .promise()
  .then(function() {
    $('.ajax-load-in-remove').css('left', '').removeClass('hide-me');
    $('.ajax-load-in-remove').last().remove();
  });

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