JavaScript Error: Uncaught TypeMismatchError

(function IIFE() {
    'use strict';
    
    var buttons = document.getElementsByTagName('button');
    
    for (let i = 0, l = buttons.length; i <= l; i += 1) {
        buttons[i].onclick = function () {
            
            for (let i = 0; i <= l; i += 1) {
                
                buttons[i].className = '';
                
                this.className = 'active';
            }
            
        };
    }
    
    
    // just for testing purpose
    for (var k = 0; k <= 10; k +=1){
        alert(k);
    }
      
}());
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Test UI</title>
    <link href="style.css" rel="stylesheet">
</head>
<body>

    <ul>
        <li><button class="active">A</button></li>
        <li><button>B</button></li>
        <li><button>C</button></li>
    </ul>
                                 
<script src="script.js"></script>
</body>
</html>

https://i.sstatic.net/H8uAc.png

I was surprised to see that the alert() function wasn't working as expected. At first, I thought everything was fine because it seemed to be functioning correctly.

Now I'm puzzled about why buttons[i] is returning undefined.

This code makes use of ES6.

Thank you for your assistance

Answer №1

I can't help but wonder why buttons[i] is undefined.

This happens because of your condition, i <= l. When i reaches the value of l, buttons[i] becomes undefined - always keep in mind that indexing starts at 0.

See it in action

(function IIFE() {
    'use strict';
    
    var buttons = document.getElementsByTagName('button');
    
    for (let i = 0, l = buttons.length; i < l; i += 1) {
        buttons[i].onclick = function () {
            
            for (let i = 0; i < l; i += 1) {
                
                buttons[i].className = '';                    
                this.className = 'active;';
            }   
        };
    }
    // just a test
    for (var k = 0; k <= 10; k +=1){
        alert(k);
    }
      
}());
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Test UI</title>
    <link href="style.css" rel="stylesheet">
</head>
<body>

    <ul>
        <li><button class="active">A</button></li>
        <li><button>B</button></li>
        <li><button>C</button></li>
    </ul>
                                 
<script src="script.js"></script>
</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

CSRF fails to execute during the initial post submission

This is my first time dealing with CSRF and reaching out to Stack Overflow for the first time. After struggling through the configuration, I finally managed to get it working almost perfectly. However, I ran into an issue where if I open a bookmarked page ...

JavaScript code to output CSS styled text: "echo"

Implementing anti-adblock on my site was necessary, as my bitcoin faucet relies on ads to function. I wrote some code to detect adblock on the client's browser: function TestPage() { if ($('.advertisement').height() == 0) var advertisement ...

I have observed that the form on an ASP.NET MVC Partial View can only be submitted after pressing the Enter key twice on the

**** Update - This issue seems to be specific to MS Edge. It functions properly with just one Enter key press on Chrome and Firefox.** I encountered a strange problem where a form only gets submitted after pressing Enter key twice in a text box. The form ...

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

Defining the scope of a variable that is accessed by multiple asynchronous callbacks

Utilizing the async.js library by Caolan McMahon and the jQueryUI progress bar, I am providing real-time feedback to users while multiple asynchronous calls gather data and populate elements in a complex graph. The lingering question is: What is the most ...

VueJS, when used in conjunction with Vuetify, might require an extra loader to handle scoped css

While attempting to compile my VueJS code using webpack, I encountered an error with the following code: <template> <v-app-bar app color="blue" flat height="100px"> <v-img class="mx-2" contain max-height="80" m ...

Utilizing Jison/Bison for string analysis

I'm currently diving into the world of Jison, a Javascript parser generator utilizing Bison syntax. My current code snippet resembles the following: a: "{{index()}}" b: "{{blah(2, 'aba')}}" My goal is to develop a parser that can interpre ...

Navigate to a different page using Angular2 routing

Looking for guidance on using redirect in the new Angular 2 router. Specifically interested in examples similar to 'redirectTo' from the beta version. Any demos on 'plnkr.co' would be greatly appreciated! ...

Detecting incorrect serialized data entries based on data types

In the scenario where the type MyRequest specifies the requirement of the ID attribute, the function process is still capable of defining a variable of type MyRequest even in the absence of the ID attribute: export type MyRequest = { ID: string, ...

What strategies can I implement to enhance my ability to navigate and comprehend extensive codebases?

I have some experience with programming, especially in creating web apps. However, when it comes to understanding code that I read, I sometimes struggle. Recently, I came across a carousel library called Glide on Github and I couldn't fully grasp its ...

conditional statement for manipulating data in javascript/html

I am working on appending results in an object as options in a datalist dropdown. While it is functioning correctly, the issue arises when not all elements have a specific level in the object consistently, impacting which results are added to the list. $( ...

Encountered a 404 error while attempting to build and serve a Vue.js project using 'npm build' in Apache Tomcat

After setting up a Vue.js project, the configuration in the package.json file looks like this: "scripts": { "serve": "vue-cli-service serve", "build": "vue-cli-service build", "lint": ...

How can I make a div overflow outside of a ul container when hovering over it?

Is there a way to make an arbitrary div nested within a ul overflow outside of the ul, even if the ul has a set width of 160px and overflow-y: hidden? The reason for setting it to overflow-y: hidden is because I need the list to be scrollable. Here is the ...

Sending data to mongodb using the fetch API and FormData method is a simple process that involves constructing

I have been trying to send data to mongoDB using the fetch API along with FormData, but encountering an error: POST https://xxxxxxxxxxxxxxxxxxxxxxxx/upload 500 (Internal Server Error) The form data in my EJS file appears as follows: <div id=" ...

Switching background image once the form is validated

Currently, I am in the process of developing a form for a website using HTML, CSS, and Angular JS. Although I have successfully achieved my desired outcome, I can't help but think that there might be a more efficient way to approach it. With that in m ...

Is it possible to conditionally call the Apollo Client in my Vue template script?

I have a scenario where I pass a query to the apollo client in my template file using a script tag. However, I want to find a more efficient way to handle this without having to specify the query every time. My idea is to pass a boolean value through a pro ...

Detection of collisions using bounding sphere method

In Three.js, each mesh (THREE.Object3D) comes with useful properties like boundingSphere and boundingBox, along with methods such as intersectsSphere and isIntersectionBox. I initially thought I could use these for simple collision detection. However, I n ...

Validation of object with incorrect child fields using Typeguard

This code snippet validates the 'Discharge' object by checking if it contains the correct children fields. interface DischargeEntry { date: string; criteria: string; } const isDischargeEntry = (discharge:unknown): discharge is DischargeEntry ...

How can I structure the response from HttpClient to make it compatible with *ngFor

I need assistance in solving a minor issue. I am working with data from a REST API, which is returned as an array of objects. After receiving this data in my service, I attempt to transform it and push it to a subject to notify my component about the arriv ...

TypeScript - ensuring strict typing for particular object keys

In my current project, I am using typescript and working on defining an interface that has the following structure: interface SelectProps<T> { options: T[]; labelKey: keyof T; valueKey: keyof T; } The type T in this interface can vary i ...