Append div under 2 levels of div

Append div under 2 levels of div

<div id='grandparent1' class='gp'>test</div>
<div id='parent1' class='p'>test</div>

<div id='grandparent2' class='gp'>test</div>
<div id='parent2' class='p'>test</div>

<div id='grandparent3' class='gp'>test</div>
<div id='parent3' class='p'>test</div>


I want to append div with id=child1 to div with id=parent1 ; div with id=child2 to div with id=parent3; div having id=child3 to div with id=parent3

it is must to check grandparent and parent id cannot just do $.("#
parent1").append("<div id='child1' class='c'>test</div>")

<div id='child1' class='c'>test</div>

<div id='child2' class='c'>test</div>

<div id='child3' class='c'>test</div>


How to do this with recursive method