Try It Editor
Tip: Press
Ctrl/⌘ + Enter
to Run
▶ Run
Reset
Copy
Download
Code
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Event Delegation</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <ul id="list"></ul> <button id="add">Add 1,000 items</button> <pre id="out"></pre> <script> $("#add").on("click", function(){ var html = []; for(var i=1;i<=1000;i++){ html.push("<li class='item'>Item "+i+"</li>"); } $("#list").html(html.join("")); }); // Single delegated handler (fast) $("#list").on("click", "li.item", function(){ $("#out").text($(this).text() + " clicked"); }); </script> </body> </html>
Output