1

I wanted when i click the button it should turn into text and clone new button.After clone object executed. Function is not working. Here is my code

jQuery

$('button').on('click', function(){
  $(this).replaceWith('<p>'+ $(this).text() +'</p>');
  $(this).clone().appendTo('body');
});

HTML

<button>1</button>
<button>2</button>
<button>3</button>

DEMO

Tukhsanov
  • 301
  • 1
  • 3
  • 15

1 Answers1

3

You need event delegation:

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

$(document).on('click','button', function(){
 $(this).replaceWith('<p>'+ $(this).text() +'</p>');
 $(this).clone().appendTo('body');
});

Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125