Tukhsanov
Tukhsanov

Reputation: 303

After clone(), function is not working. jQuery

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

Upvotes: 1

Views: 1260

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82231

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

Upvotes: 3

Related Questions