Click here to Skip to main content
14,735,324 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
In my website https://www.example.com , on a button click event (in jQuery) I am populating a dynamically created html UL Li list.
It is working fine but when I am using jQuery click event on dynamically created ul Li, it is not working.

What I have tried:

The code is as follows:
$(document).ready(function() { $('ul.cls-ul li').click(function(e) { alert(this); }); })
Is there any better solution?
Posted
Updated 18-May-20 4:48am
v2

It depends how your dynamically generated ul is being created. The $(document).ready() function is called once the DOM of the page has finished being built. If your ul is being built from an AJAX statement or some other ready() callback then you'll need to register the click() once the generated li elements have been generated.

The call to register $('ul.cls-ul li').click() will not register the click handler for elements added in the future, so make sure to call this after the li elements have been generated and added to the HTML of your page.
   
You're using a "direct" event handler. It will only be attached to elements which already exist when the statement runs. If you create another element later and add it to the page, the event handler will not be attached.

Use a delegated event handler instead:
$(function(){
    $(document).on("click", "ul.cls-ul li", function(e) { alert(this); });
});
.on() | jQuery API Documentation[^]

NB: You should also pay attention to the notes in the ready documentation:
jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:
  • $( handler )
  • $( document ).ready( handler )
  • $( "document" ).ready( handler )
  • $( "img" ).ready( handler )
  • $().ready( handler )

As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900