Francy Grillo
Francy Grillo

Reputation: 99

Retrieve a specific parent of child button using jQuery

I have this html structure (very general), the id of the div is added dynamically, by a function that creates sequential objects made this way:

 <div id="mydiv1">
     <div> Stuff</div>
     <div>
        <button id="remove"></button>
     </div>
 </div>

The button "remove" should remove the div where he is, so I have to retrieve the id of the div to do it. I do not know how. How can you make using jQuery? thank you

<form>
   <div id="mydiv1">
     <div> Stuff</div>
     <div>
        <button id="remove"></button>
     </div>
   </div>
   <div id="mydiv2">
     <div> Stuff</div>
     <div>
        <button id="remove"></button>
     </div>
   </div>
</form>

I tried:

("#remove").click(function(event) {
    var id = event.target.id;
}

But the result is: "remove" instead of "mydiv1" or "mydiv2"

Upvotes: 0

Views: 63

Answers (4)

Think Different
Think Different

Reputation: 2815

Try

$('.remove').click(function() {
  var id = $(this).parent().parent().attr('id');
  //This will give you the id
});

For the next part of your question try this:

$(document).on('click','.remove',function() {
  var id = $(this).parent().parent().attr('id');
  //This will give you the id
});

Upvotes: 0

sideroxylon
sideroxylon

Reputation: 4416

You should use class instead of id for the buttons (id should be unique):

$('.remove').click(function() {
  $(this).closest('div[id^="mydiv"]').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
  <div id="mydiv1">
    <div>Stuff 1</div>
    <div>
      <button class="remove">REMOVE</button>
    </div>
  </div>
  <div id="mydiv2">
    <div>Stuff 2</div>
    <div>
      <button class="remove">REMOVE</button>
    </div>
  </div>
</form>

EDIT: Updated to new code posted by OP

Upvotes: 2

Fares M.
Fares M.

Reputation: 1538

Use $(this).parent('div') to get the first parent node of type <div>

$("#remove").click(function(event) {
    var parent = $(this).parent('div');
    parent.remove();
}

EDIT

So add a class to your divs, let say .divRow for example

<form>
    <div id="mydiv1" class="divRow">
       <div> Stuff</div>
       <div>
           <button id="remove"></button>
       </div>
    </div>
    <div id="mydiv2" class="divRow">
       <div> Stuff</div>
       <div>
           <button id="remove"></button>
       </div>
    </div>
</form>

and your javascript would be in this case

$("#remove").click(function(event) {
    var parent = $(this).parent('.divRow'),
            id = parent.attr("id");
    alert(id);
    parent.remove();
}

Upvotes: 0

Vdomah
Vdomah

Reputation: 46

For mydiv2 change button like this:

$(".remove").click(function() {
    var id = $(this).data('id');
    $("#mydiv"+id).remove();
}
<button class="remove" data-id="2"></button>

Upvotes: 0

Related Questions