Execute a script when the element is being clicked in HTML?


Use the onclick attribute to execute a script when the element is clicked in HTML.

Example

You can try to run the following code to implement onclick attribute −

<!DOCTYPE html>
<html>
   <body>
      <button onclick = "display()">Click</button>

      <p id = "test"></p>

      <script>
         function display() {
            document.getElementById("test").innerHTML = "You clicked the button!";
         }
      </script>
   </body>
</html>

Updated on: 03-Mar-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements