jQuery Dynamically Create Elements and Attached Events
jQuery Dynamically Create Elements and Attached Events
Published
Event binding on dynamically created elements
In this lesson you will learn how to dynamically create HTML elements and attached events to it. Also, the Event binding on dynamically created elements is really important to understand to develop a good application.
Code Example
<div id="result"></div>
<br>
<button id="addExpense">Add Expense</button>
<script src="https://code.jquery.com/jquery-git.js"></script>
<script>
$("#addExpense").click(function(){
let newExpense = document.createElement("div");
let expense_id = $("*[id*='expense_']").length +1;
newExpense.id = "expense_" + expense_id;
newExpense.className = "clsExpense";
newExpense.innerHTML = "Expense " + expense_id;
$("#result").append(newExpense);
});
$(document.body).on("click", ".clsExpense", function(event){
console.log(this.id +" div just clicked!!");
});
</script>