Delete div from grandson Jquery

0

I have this sequence of divs

<div class="abuelo1">
      <div class="padre">
           <div class="nieto1">
           <div class="nieto2">
      </div>
</div>

The thing is that by means of a grandchild2 I want to eliminate grandpa1 with its content, while through grandchild1 I want to add a grandpa2 under grandpa1 with all the structure he has (Note: there is only one grandchild1 and grandchild2 for each grandparent , I do not want to add more). Any idea how to do it? I know that with

$(".nieto2").click(function () {
    $('this').parent().remove(); 
}); 

eliminate only the "father" div, but I also want to eliminate the grandfather.

As they are going to be added and deleted dynamically, I want to eliminate and add grandparents from their own grandchild, not in general.

    
asked by EriK 26.09.2017 в 19:06
source

2 answers

3

To eliminate a grandparent you just have to call parent twice. Think of real life, father's father who is he?

  • This does not have to be in quotes. There is no item named this.
  • The divs you have to close. Remember that there are self-closing labels <br/> And others that you have to put a closing% <div></div> .
  • $(".nieto1").click(function () {
        $(this).parent().remove();
    }); 
    $(".nieto2").click(function () {
        $(this).parent().parent().remove();
    }); 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    
    <div class="abuelo1">abuelo1
          <div class="padre">padre
               <div class="nieto1">nieto1</div>           
               <div class="nieto2">nieto2</div>
          </div>
    </div>
        
    answered by 26.09.2017 / 19:10
    source
    0

    To do the traversing up, without needing to know if you are the grandson or great-grandchild, or great-great grandson.

     $(this).parents('.abuelo1').remove();
    
        
    answered by 28.09.2017 в 15:07