Why doesn't the click event work when I click the btn class a second time?

 $(function() { $('.btn').on('click', function() { if ($(this).attr('name') == 'first') $(this).replaceWith('<button class="btn" name="second">2</button>'); else $(this).replaceWith('<button class="btn" name="first">1</button>'); }) }) 
 .btn { padding: 5px 15px; border: 1px solid #ddd; cursor: pointer; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="btn" name="first">1</span> 

    1 answer 1

     $(function(){ $(document).on('click', '.btn', function(){ console.log($(this).attr('name')); if ($(this).attr('name') == 'first') $(this).replaceWith('<button class="btn" name="second">2</button>'); else $(this).replaceWith('<button class="btn" name="first">1</button>'); }); }); 
     .btn { padding: 5px 15px; border: 1px solid #ddd; cursor: pointer; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span class="btn" name="first">1</span> 

    • Now it works, but this has stopped working. How to find out on which element the event was executed? - Cristian
    • @Cristian That you accidentally broke something. - Igor
    • indeed, I forgot that I changed .on('click') to .click() . Likely function .click() does not accept such parameter. - Cristian