0

im trying to replace various elements with another inside a jquery .each loop and give them on click events to their child nodes, but it does not work, here is my code.

var replacer = function () {
  var elementbody = "<div class='Container'><div class='Button'></div></div>";
  $('.myclass').each(function (index, element) {
    $(element).replaceWith(elementBody);
    $(element).find('.Button').click(function () {
  //------------------To do on click event------------------//
});
};

2 Answers2

0

After you use

$(element).replaceWith(...);

element still refers to the old element, not the elements that have replaced it. So $(element).find('.Button') doesn't find the button you just added.

Instead of adding the handler to each element that you add, use delegation to bind a handler just once, as explained in Event binding on dynamically created elements?

$("someSelector").on("click", ".Button", function() {
    ...
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You can use a delegate as Barmar suggests or you could provide yourself with a new jquery object that references your new content before running the replaceWith

Something like this, maybe:

new_element = $('<div><button>Hello World</button></div');
$(element).replaceWith(new_element);
new_element.find('button').on('click', function(e) {
    console.log(e);
});
refeniz
  • 525
  • 1
  • 5
  • 14