user3006927
user3006927

Reputation: 476

jQuery, remove isn't removing the child elements—just the parent

I have a function that appends elements to the body on a click event. Then there is another one that should remove those elements when one of the elements that was appended previously is clicked.

when I click on the .closeBigPic that element is removed as expected, but the .bigPicWrapper div is removed and the .bigPic element stays behind.

$(document).on('click', '.user-profile .avatar_section', function() {
    var thumbUrl = $(this).find('.avatar_profile').attr('src');

    var origUrl = thumbUrl.replace('thumb', 'medium');
    console.log(origUrl);

    $('body').append('<div class="closeBigPic"></div><div class="bigPicWrapper"><img class="bigPic" src="' + origUrl + '" /></div>')
});


$(document).on('click', '.closeBigPic', function() {
    $(this, '.bigPicWrapper').remove();
});

Not sure why it would be necessary but here is the scss just in case:

    .user-profile {
    .avatar_section {
        cursor: pointer;
    }
}

.bigPicWrapper {
    position: absolute;
    z-index: 9010;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);

    img {
        max-width: 100%;
        border-radius: 100%;
        border: solid 5px #fff;
    }
}

Shouldn't .remove() remove the child elements as well.

UPDATE:

When I change the second click event to:

$(document).on('click', '.closeBigPic', function() {
    $(this).remove();
    $('.bigPicWrapper').remove();
});

It works exactly as expected. What is going on there? I imagine it has something to do with being coupled with this

Upvotes: 0

Views: 95

Answers (2)

Penguin Brian
Penguin Brian

Reputation: 2131

I don't think the following does what you think it does:

$(this, '.bigPicWrapper')

From the documentation:

jQuery( selector [, context ] )

It doesn't look like '.bigPicWrapper' is a valid context.

Upvotes: 0

Cody.Stewart
Cody.Stewart

Reputation: 577

$(document).on('click', '.closeBigPic', function() {
  $(this, '.bigPicWrapper').remove();
});

This is saying to use .bigPicWrapper as your context. Were something like

$('.foo, .bar').remove();

is simply acting as a css selector.

Upvotes: 1

Related Questions