Search code examples
javascriptjquerycode-injection

Removing html with jquery & and removing container if class exists in any element inside


I am working with a list of people. "Friends" and "Not Friends"

Each container represents a person. If the person is my friend it will have a button that says "remove friend" if the person is not a friend; it will have a button that says "add friend"

Each person container contains both the "Remove Friend" and "Add Friend" buttons. If the person is a friend the "remove friend" button will have an addition class of "hidden-element" and if the person is not my friend the "add friend" button will have the same class of "hidden-element"

Goal: Only show people who are not my friends.

Attempt:

For the .hidden-element class I want to remove the html completely. (not just hide its display). To accomplish that i used $('.hidden-element').remove(); which i think removes all buttons with the class of ".hidden-element" from the html?

To identify which person is a friend and which person is not a friend. I removed all elements with the class of ".hidden-element" Leaving only the visible button left in the ".person" container. To accomplish that i used $('.hidden-element').remove(); which i think removes all buttons with the class of ".hidden-element" from the html.

Now i want to remove all elements with the class of ".person" ONLY IF they contain anywhere inside them, an element with the class of ".remove-friend"

so i tried this:

if($('.person').find('.remove-friend').length) {
            $( '.person' ).remove();
}

Which just removed ALL elements with the class of ".person" which is not what I want. Because I want ONLY people who are NOT FRIENDS to show on the front-end


HERE IS A FULL JS FIDDLE

Change the .remove to .show in the Jquery to see the html layout for a better understanding.


Solution

  • Just do :

    $('.remove-friend').parents('.person').remove()
    

    here's a fiddle https://jsfiddle.net/nwop13L9/40/

    But as @CalvinNunes said -> juste do $('.friend').remove();

    even simpler