jQuery on() bind click event to dynamically created elements

Introduction

jQuery click() method only bind the click event to the existing elements.

To bind the click event to existing and future elements, use the jQuery on() method.

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

View in separate window

<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery Bind Click Event to Dynamically added Elements</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(document).ready(function(){
        $("button").click(function(){
            $("ol").append("<li>list item <a href='javascript:void(0);' class='remove'>&times;</a></li>");
        });// w w w . j a  v a 2 s.  c om
        $(document).on("click", "a.remove" , function() {
            $(this).parent().remove();
        });
    });
</script>
</head>
<body>
    <button>Add new list item</button>
    <ol>
        <li>list item</li>
        <li>list item</li>
        <li>list item</li>
    </ol>
</body>
</html>



PreviousNext

Related