YogeshChauhan.com
How to add onclick event to html elements dynamically using JavaScript?
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();

dreamhost

Leave a Reply

Most Read

#1 How to check if radio button is checked or not using JavaScript? #2 How to set opacity or transparency using CSS? #3 Pagination in CSS with multiple examples #4 How to make HTML form interactive and using CSS? #5 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #6 How to uninstall Cocoapods from the Mac OS?

Recently Posted

Mar 3 How to embed YouTube or other video links in WordPress? Mar 3 How to change the Login Logo in WordPress? Mar 3 substring() Method in JavaScript Mar 3 Window setInterval() Method in JavaScript Mar 2 How to zoom an element on hover using CSS? Mar 2 the box-sizing property in CSS

You might also like these

How to create a sticky menu pin using CSS?CSSHow to detect the Blog Page in WordPress?WordPressSQL GROUP BY StatementSQL/MySQLHow to make a UILabel clickable in Swift 5?SwiftModules and its Core features in JavaScriptJavaScript5 Ways to Loop Through JavaScript ArraysJavaScriptLearn to Establish Connection using MySQLi (object-oriented), MySQLi (procedural) and PDO with Example CodePHPThe difference between isFinite() method and isFinite() function in JavaScriptJavaScriptCan We Use For Loop to Loop Through Associative Arrays in PHP?PHPAggregate Functions Examples in Postgres for BeginnersPostgresClearwater Seafoods – B2C in ChinaMiscSolution for the error Commit failed – exit code 1 received in Desktop GithubMisc