Yogesh Chauhan's Blog

How to add onclick event to html elements dynamically using JavaScript?

in JavaScript on February 13, 2021

There are few ways we can do this.

Using addEventListener

The first one is simple function call targeting the element.

const el = document.getElementById("element");

el.addEventListener("click", function, false);

Read more about addEventListener on MDN

Using setAttributes

In this post, I demonstrated how we can create HTML elements with id and class. Same way we can use setAttributes to add an onclick event function.

We can also use setAttributes on the element that already exists.

Just like this:

const el = document.getElementById("element");


Using onclick

This is a straightforward approach.

const el = document.getElementById("element");

el.onclick = function();

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #3 How to add Read More Read Less Button using JavaScript? #4 How to uninstall Cocoapods from the Mac OS? #5 PHP Login System using PDO Part 1: Create User Registration Page #6 How to Use SQL MAX() Function with Dates?

Recently Posted

#Aug 15 Is PHP still good for back-end programming? #Aug 10 How to create a multisite network in WordPress? #Aug 3 How to create a circle that follows a cursor using JavaScript and CSS? #Aug 3 How to make a curtain slider using jQuery and CSS? #Aug 2 How to progressively load images and add a blurry placeholder? #Aug 1 How to create a placeholder loader (throbber) using CSS?
You might also like these
SQL Right JoinSQL/MySQLAlternate Style Sheets in CSSCSSHow to compress images with gulp in WordPress?WordPress@forward rule in SCSS (Sass)SCSSHow to add multiple components in React app?ReactHow to convert a number rounding to a specified number of decimals in JavaScript?JavaScriptHow to add Laravel to WordPress using Sage theme (and install Tailwind CSS)?PHPHow to Secure Web or Mobile Browsers?MiscellaneousConfiguring Modules with @forward rule in SCSS (Sass)SCSSA quick introduction to API, REST API and PostmanMiscellaneousMySQL queries to get data rows from previous month as well as from last 30 daysSQL/MySQLSlider animation using CSS transform propertyCSS