简体   繁体   中英

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. :)

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.

Make sure your javascript is loaded after DOM load .

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

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();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM