How to bind click event to dynamically created HTML elements in jQuery

Topic: JavaScript / jQuery« Prev|Next »

Answer: Use the jQuery on() method

If you try to do something with the elements that are dynamically added to DOM using the jQuery click() method it will not work, because it bind the click event only to the elements that exist at the time of binding. To bind the click event to all existing and future elements, use the jQuery on() method. Check out the following example.

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>jQuery Bind Click Event to Dynamically added Elements</title>
  • <script src=""></script>
  • <script type="text/javascript">
  •     $(document).ready(function(){
  •         $("button").click(function(){
  •             $("ol").append("<li>list item <a href='javascript:void(0);' class='remove'>&times;</a></li>"); 
  •         });
  •         $(document).on("click", "a.remove" , function() {
  •             $(this).parent().remove();
  •         });
  •     });
  • </script>
  • </head>
  • <body>
  •     <button>Add new list item</button>
  •     <p>Click the above button to dynamically add new list items. You can remove it later.</p>
  •     <ol>
  •         <li>list item</li>
  •         <li>list item</li>
  •         <li>list item</li>
  •     </ol>
  • </body> 
  • </html>

Related FAQ

Here are some more FAQ related to this topic:


Your Feedback:


We would love to hear from you! Please say something.