Heapcoding

How to bind click event in JQuery for dynamically added HTML element

Published November 19, 2021

In this tutorial I shall show you how to bind click events in jquery for dynamically added html element.

Let’s start step by step

Create a new html document

How to bind click event in JQuery for dynamically added HTML element

In the above screenshot you will see I have created the basic HTML document. That contains some basic HTML tags that are necessary to create the HTML document.

  • On line #01, There is a HTML5 declaration tag that represents that it is an html5 document.
  • On line #02, I have added the head tag that is the necessary tag to add some metadata about the document and also the css for styling too.
  • On line #04, I have added the body tag, where we will write our code.

Add JQuery in HTML document

How to bind click event in JQuery for dynamically added HTML element

In the above screenshot you will see I have added the JQuery CDN from JQuery’s official website

We need to write JQuery in our code that’s why we have added the JQuery in our code.

Dynamically add an HTML element to document using JQuery

In the above code you can see I have created a button and appended to the body using JQuery. 

Now let’s render our code in the web browser to see if the button added to our body.

How to bind click event in JQuery for dynamically added HTML element

In the above screenshot you can see a button with text “click me”.

Bind click event in jquery for dynamically added button element

How to bind click event in JQuery for dynamically added HTML element

In the above screenshot you can see that I have added a click event to our button.

On line #12 you will see I have added a click event by using button id that is “my-btn”.

When you click on the button an alert dialog box will be shown with the text message “Button clicked”.

Now let’s render it on the web browser to see if it is working as expected.

How to bind click event in JQuery for dynamically added HTML element

Congratulations you have added a click event to dynamically created html element using JQuery.