Open In App

Click() method not working and Console returns an error message in JavaScript

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will see “Uncaught TypeError: document.getElementsByClassName(…).click is not a function” error created while using click() method in JavaScript. 

The TypeError is an object that represents an error that arises when the operation can not be performed due to the value is not of the expected type.

Approach: First double-check that you have written a document.getElementsByClassName not document.getElementByClassName. If you spelled it correctly then probably this error arises because you are not aware that document.getElementsByClassName returns an array of elements, not a single element. In order to avoid the error, you need to access a single element and then perform a click().

Example: The following code example creates the above Uncaught TypeError because we have not accessed an individual element yet.

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script>
        function btnA() {
            document.getElementById('result').innerHTML = 
            "You've successfully clicked on the button";
        }
      
        function btnB() {
            document.getElementsByClassName('active').click();
        }
    </script>
</head>
  
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h3>Generates a TypeError</h3>
    <div id="result"></div>
    <button class="active" 
            onclick="btnA();">
        Button A
    </button>
    <button class="trigger" 
            onclick="btnB();">
        Button B
    </button>
</body>
</html>


Output: This error pops up when we click on button B.

 

Example: This example resolves the above TypeError by accessing an individual element. This code resolves the above mentioned TypeError just by specifying an individual element in document.getElementsByClassName().

HTML




<!DOCTYPE html>
<html>
  
<head>
    <script>
    function btnA() {
        document.getElementById('result').innerHTML = 
        "You've successfully clicked on the button";
    }
  
    function btnB() {
        document.getElementsByClassName('active')[0].click();
    }
    </script>
</head>
  
<body>
    <h1 style="color:green">
        GeeksforGeeks
    </h1>
    <h3>Resolving a TypeError</h3>
    <div id="result"></div>
    <button class="active" 
            onclick="btnA();">
        Button A
    </button>
    <button class="trigger" 
            onclick="btnB();">
        Button B
    </button>
</body>
</html>


Output:  Now when button B is clicked, instead of an error, it displays the message “You’ve successfully clicked on the button”.

 



Last Updated : 26 Jun, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads