JavaScript Code

How to set onclick listener for a div using JavaScript?

Tutorials using JS

Set onclick listener for a div in JavaScript

In this tutorial, you will learn how to set onclick listener function for a div element in JavaScript.


To set onclick listener for a div element using JavaScript, we can use Element.addEventListener() method. Get the div element, call addEventListener() on the div element, and pass "click" value for first argument, and a function for second argument.

divElement.addEventListener("click", someFunction);

When user performs click action on the div element divElement, someFunction() will be called.


1. In the HTML code, we have a div element with id myDiv. When user clicks on this div element, we set to call the function addParagraphToDiv().

<!DOCTYPE html>
<h1>JavaScript Tutorial</h1>
<h2>Add On-click Listener</h2>
<button id="myBtn">Click me</button>
<div id="myDiv"></div>

//set onclick listener for #myBtn
document.getElementById("myBtn").addEventListener("click", function() {
	//get div element
	const myDiv = document.getElementById("myDiv");
	//add paragraph to div element
    myDiv.innerHTML += "<p>Hello World</p>";


Copyright @2022