jQuery

How to bind onclick event to dynamically added HTML element with jQuery

In this tutorial, we are going to see how to bind onclick event to dynamically added HTML element with jQuery. If you try to bind the elements that are dynamically added to the DOM using the click() method of jQuery, this will not work, because it only binds the click event to elements that exist at the time of the “binding”. To bind the click event to all existing and future elements, use jQuery’s on() method. see the following example.
 

HTML Code:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Bind onclick event to dynamically added element</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript">
		  // Put the jQuery code Here
    </script>
  </head>
  <body>
    <p>Click the button below to dynamically add new items. You can remove it later.</p>
    <button>+ Add</button>
    <ul>
      <li>Lorem Ipsum</li>
      <li>Lorem Ipsum</li>
      <li>Lorem Ipsum</li>
    </ul>
  </body> 
</html>

 

jQuery Code:
$(document).ready(function(){
        //Add item
        $("button").click(function(){
          $("ul.test").append("<li>Lorem Ipsum <a href='javascript:void(0);' class='delete'>×</a></li>"); 
        });
        //Delete item
        $(document).on("click", "a.delete" , function() {
          $(this).parent().remove();
        });
});
Result

Click the button below to dynamically add new items. You can remove it later.

  • Lorem Ipsum
  • Lorem Ipsum
  • Lorem Ipsum
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *