Kris
Kris

Reputation: 3769

How to remove div element with jQuery

when I want to remove div element, I have the following code:

<div class='text-field'>
     <input type='text' />
     <input type='button' class='remove-btn' />
</div>
<div class='text-field'>
     <input type='text' />
     <input type='button' class='remove-btn' />
</div>
<div class='text-field'>
     <input type='text' />
     <input type='button' class='remove-btn' />
</div>
<div class='text-field'>
     <input type='text' />
     <input type='button' class='remove-btn' />
</div>

when i click remove-btn, its parent div text-field should be removed. i have this code but it doesnt work.

$(".remove-btn").click(function(){
    $(this).parent().remove();
});

thanks for any help. :)

Upvotes: 0

Views: 6767

Answers (3)

Jazaret
Jazaret

Reputation: 3705

After reading your comment here is what you should do:

$("#add-file-field").click(function() {
    $("#text").append("<div class='text-field'><input type='text' /> <input type='button' class='remove-btn' value='remove' /></div>");
});

$(".remove-btn").live('click',function() {
    $(this).parent().remove();
});

Upvotes: 1

David
David

Reputation: 218808

The most common cause for this is that you may be trying to bind to the click event before the element has been loaded in the DOM. Try wrapping your jQuery code in:

$(document).ready(function() {
  // your code here
});

There's also the .live() function which will bind to elements which are added to the DOM at a later time.

Upvotes: 4

Niklas
Niklas

Reputation: 30002

Make sure your javascript is loaded after DOM load.

$(function(){
 $(".remove-btn").click(function(){
    $(this).parent().remove();
 });
});

Upvotes: 2

Related Questions