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");

el.setAttribute("onclick","function");

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
Relative Length Units in CSSCSS5 Ways to Loop Through JavaScript ArraysJavaScriptA Step by Step Guide to Make RSS in XML For Any Website or Blog For FreeMiscellaneousHow to create and store JSON objects in localStorage using JavaScript?JavaScriptWhat are Controlled Components in React?React5 Key Principles Of Good Website UsabilityUI/UXWindow setInterval() Method in JavaScriptJavaScriptAdd animated hamburgers menu using Hamburgers collection on GitHubCSSHow to create a Child Theme in WordPress?WordPressHow to host Google fonts on your server and add them using CSS?CSSHow to get Current Hour, Minute and Second in JavaScript?JavaScriptHow to insert Bootstrap 4 in Angular 9 app?Angular