YogeshChauhan . com

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

amazon

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 How to Use SQL MAX() Function with Dates? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

Jun 16 What are Stored Procedures for SQL Server? Jun 16 What are Class Constants in PHP? Jun 15 A short basic guide on states in React Jun 15 How to define constants in PHP? Jun 15 How to define visibility for a property in PHP? Jun 15 How to use @if and @else in SCSS?

You might also like these

Arbitrary Arguments in SCSS functionsSCSSIN and BETWEEN Operators in SQLSQL/MySQLHow To Create a Fullscreen Background Video using CSS and JavaScript?CSSHow to render lists inside a component in React?ReactHow to remove special characters (dash, asterisk etc) from any string in PHP?PHPHow to add a scroll back to top button using JavaScript and CSS?CSSSolution to Could not cast value of type ‘NSTaggedPointerString’ to ‘NSNumber’SwiftHow to create a simple stopwatch using JavaScript?JavaScriptHow to check if radio button is checked or not using JavaScript?JavaScriptThe flex-grow, flex-shrink and flex-basis Properties in CSSCSSHow to change the Login Logo in WordPress?WordPress3 ways to pass a variable in url() function in SCSS (Sass)SCSS