In this tutorial we will learn how to trigger a click event for dynamic li tag. Since jQuery click() method doesn't work for dynamically created li tag, we can use jQuery on() method to bind click event with dynamic li elements.
Table of Contents
on() method
jQuery on() method attaches one or more events with the HTML elements.
on() method is mainly used to attach the click event and other events with the elements that are created dynamically, by the user with help of script.
HTML Code
HTML Code is given below, in this code we have a ul tag with three list items and a button tag to dynamically add more list items. This is done using click() method and append() method.
<!DOCTYPE html>
<html>
<head>
<title>jQuery Dynamic li Click Event</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<ul id="list">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
<button id='btn'>Add Li Tags</button>
<script src="script.js"></script>
</body>
</html>
JQuery Code
JQuery Code is given below, jQuery click() method is used to tie the execution of code with click event of button tag.
append() method is used to add HTML tag or HTML content at the end of selected HTML element.
In this example it is adding more li tags dynamically.
on() method is then used to add click event on all li tags including dynamic li tags and static li tags. This click event will execute a function to change background of all list items.
This is not possible with click() method since it will only add event to static li tags, it doesn't work for dynamic ones.
<script>
$(document).ready(function() {
var count = 0;
$('#btn').click(function() {
count = count + 1;
$("#list").append("<li>Dynamic Li Tag " + count + "</li>");
});
$("#list").on("click","li",function() {
$(this).css("background-color", "red");
});
});
</script>
In second example all we have used click() method to target all li tags but the code inside click() method will not run for dynamic list items and it will only change background of other li tags.
<script>
$(document).ready(function(){
var count = 0;
$('#btn').click(function(){
count = count + 1;
$("#list").append("<li>Dynamic Li Tag " + count + "</li>");
});
$("#list li").click(function(){
$(this).css("background-color", "red");
});
});
</script>
Demo
Video Tutorial
Watch video tutorial on How To add Click event on Dynamic li tags with jQuery.