Open In App

Uncaught ReferenceError at HTMLButtonElement.onclick

Improve
Improve
Like Article
Like
Save
Share
Report

In this article article, let’s first discuss the Reference error and then come to onclick function and then we come over the question Uncaught ReferenceError at HTMLButtonElement.onclick using example and lastly come to the solution approach.

Onclick Function in javaScript:

  • The onclick event handlers are a group of properties offered by DOM elements to help manage how that element reacts to events.
  • The ‘target’ represents the element on which the event is added/attached.
  • The ‘functionRef’ represents the function name or a function expression. The function receives an argument of an ‘Event’ object.

Syntax:

target.on<event> = functionRef;

when does onclick work: The click event occurs when the user clicks on an element. The click event is completed when the mouse button is pressed and released on a single element.

Reference Error: The error which represents when a variable or function does not exist in the current scope and is referenced through a script tag in javascript.

Message: Uncaught ReferenceError:something is not defined 

Example 1: Let’s come over an example when Uncaught ReferenceError happens at HTMLButtonElement.onclick.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
 
    <button id="out" onclick="listen(this)">
          Submit
      </button>
</body>
<script>
    function listen(this) {
        this.style.backgroundColor = 'red';
        this.innerHTML = "Hii GFG , How r u???"
    }
</script>
</html>


Output:

 

Here error arises due to this passing during function definition but inside a function, this refers to the window object not the id of that element. so it creates an issue and returns an error on the console and the program does not give the desired output.

Example 2: This is the solution to the above issue that arises in JavaScript:

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible"
          content="IE=edge">
    <meta name="viewport"
          content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
 
<body>
 
    <button id="out" onclick="listen(this)">
          Submit
      </button>
</body>
<script>
    function listen(get) {
        console.log(this)
        get.style.backgroundColor = 'red';
        get.innerHTML = "Hii GFG , How r u???"
    }
</script>
</html>


Output:

 

Here does not create an issue because passing any random parameter as an argument in the function definition does not pass this as an argument.



Last Updated : 22 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads