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 How to add Read More Read Less Button using JavaScript? #3 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #4 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
WordPress: How to get field values in Advanced Custom Fields?WordPressHow to create a multisite network in WordPress?WordPressHow to get the full URL of current page in PHP?PHPHow to create and store JSON objects in localStorage using JavaScript?JavaScriptList of social media icon logo color codes in HEXMiscellaneousWhat are Identifiers in JavaScript?JavaScriptEffects in ReactReactQuick Introduction to 11 Array Iteration Methods in JavaScriptJavaScriptDebugging in WordPress Part 2: WP_DEBUG_LOG and WP_DEBUG_DISPLAYWordPressReverse a String in JavaScriptJavaScriptWhat is React? Learn the basicsReactGive buttons accessible namesUI/UX