Click here to Skip to main content
15,889,706 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:
JavaScript
$(document).ready(function() { $('ul.cls-ul li').click(function(e) { alert(this); }); })
Is there any better solution?
Posted
Updated 18-May-20 3: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.
 
Share this answer
 
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:
JavaScript
$(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.
 
Share this answer
 

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



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