-1

Hi I am learning jQuery and I do not understand why this fucntion does not work. When I click the button it should remove the div but it does not.

The remove function

$(".editButton").click(function () {
    $(".editButton").remove();
});

Function that creates the div

var formatPost = function (d) {
    var s = '';
    s = '<div class="post" data-id="' + d.id + '"><h2 class="postHeading">' + d.title + '</h2>';
    s += d.body;
    s += '<p> Posted on: ' + d.date + '</p>';
    s += '<div class="btn editButton">Edit Post</div>'
    s += '</div>'
    return s;
};
ozil
  • 6,930
  • 9
  • 33
  • 56
Pavel Kašelják
  • 351
  • 3
  • 17

3 Answers3

3

Currently you are using direct binding, this works when the element exist on the page at the time your code makes the event binding call.

You need to use Event Delegation using .on() delegated-events approach.

i.e.

$(document).on('event','selector',callback_function)

Use,

If you want to remove only button

$(document).on('click', '.editButton', function () {
    $(this).remove(); 
});

If you want to remove complete post, First, You need to execute the action in current element context so use this. Then use closest() to find post parent and then use .remove()

$(document).on('click', '.editButton', function () {
    $(this).closest('.post').remove(); 
});
Satpal
  • 132,252
  • 13
  • 159
  • 168
1

Use Event Delegation.

You added the edit button dynamically. DOM didn't know when was the element is added so we need to traverse from the document or the body or Immediate parent selector to find the element

$(document).on('click', '.editButton', function () {
    $(this).remove();
});
Sudharsan S
  • 15,336
  • 3
  • 31
  • 49
1

Since you are dynamically creating div, use event delegation

$(document).on('click', '.editButton', function () {
    $(this).remove();
});
Zee
  • 8,420
  • 5
  • 36
  • 58