Open In App

HTML DOM onclick Event

The HTML DOM onclick event occurs when the user clicks on an element. 

There are three ways to add onclick events:



Syntax:

In HTML:



<element onclick="myScript">

In JavaScript:

object.onclick = function(){myScript};

In JavaScript, using the addEventListener() Method:

object.addEventListener("click", myScript);

Example 1: Using HTML 




<center>
    <h2>HTML DOM onclick Event in Html</h2>
    <button onclick="myFunction()">Click me</button>
    <p id="gfg"></p>
  
    <script>
        function myFunction() {
            document.getElementById(
            "gfg").innerHTML = "GeeksforGeeks";
        }
    </script>
</center>

Output:

 

  Example 2: Using JavaScript 




<center>
    <h2>HTML DOM onclick Event</h2>
    <p id="gfg">Click me.</p>
  
    <script>
        document.getElementById("gfg").onclick = function() {
            GFGfun()
        };
          
        function GFGfun() {
            document.getElementById(
            "gfg").innerHTML = "YOU CLICKED ME!";
        }
    </script>
</center>

Output:

 

Example 3: In JavaScript, using the addEventListener() method: 




<center>
    <h2>HTML DOM onclick Event</h2>
    <p id="gfg">Click me.</p>
  
    <script>
        document.getElementById(
        "gfg").addEventListener("click", GFGfun);
          
        function GFGfun() {
            document.getElementById(
            "gfg").innerHTML = "YOU CLICKED ME!";
          document.getElementById(
            "gfg").style.color = 'red';
          document.getElementById(
            "gfg").style.background = 'cyan';
        }
    </script>
</center>

Output:

 

HTML DOM onclick event supports All HTML elements, 

Except: 

<base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style>, and <title>

We have a complete list of HTML DOM methods, to check those please go through this HTML DOM Object Complete reference article.

Supported Browsers: The browsers supported by DOM onclick Event are listed below.

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.


Article Tags :