What could be the reason for encountering a TypeError while attaching event listeners using a for loop?

When attempting to add a "click" event listener to a single element, it functions correctly:

var blog1 = document.getElementById("b1");

blog1.addEventListener("click", function(){
window.location.href="blog1.html";
});

However, when I try to use a for loop to assign click listeners to multiple elements at once in the following manner:

var blog1 = document.getElementById("b1");
var blog2 = document.getElementById("b2");
var blog3 = document.getElementById("b3");

for(var i = 1; i < 4; i++){
var k = ("blog" + i);
k.addEventListener("click", function(){
window.location.href = (k + ".html");
 });
 }

I encounter the error:

TypeError: k.addEventListener is not a function

Could someone please help me identify where my mistake lies? Thank you so much. P.S- Attempting to achieve this using vanilla JS.

Answer №1

By using the code snippet <code>var k= ("blog" + i );
, you can generate strings like blog1, blog2, blog3. It does not specifically reference elements. To improve performance, consider using document.getElementById() directly in a loop and utilize let instead of var.

for(let i =1; i<4; i++){
 let blog = document.getElementById("b"+i);
   blog.addEventListener("click", function(){
     window.location.href=(i+".html");
   });
}

Answer №2

One option is to utilize the eval function, which allows for the evaluation of a string as JavaScript code during runtime.
Reference: eval.

var blog1 = document.getElementById("b1");
var blog2 = document.getElementById("b2");
var blog3 = document.getElementById("b3");

for(var i =1; i<4; i++){
    var k= eval("blog" + i );
        k.addEventListener("click", function(){
        window.location.href=(k+".html");    
    });
}

It's important to exercise caution when using eval, as it can lead to performance and code injection issues. Ref: When is JavaScript's eval() not evil?.

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

Having trouble retrieving JSON data from an external source

I'm currently facing a challenge where I am unable to fetch JSON data from a webpage despite multiple attempts. I keep encountering the following errors: Uncaught SyntaxError: Unexpected token : or XMLHttpRequest cannot load URL. No 'Access-Co ...

Why does jQuery's each function struggle to retrieve the width of hidden elements?

Why is it difficult to obtain the width of hidden elements? Here is my code: .hidden { display: none; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script> <ul class="navbar-items"> <li> ...

Postman sends requests by utilizing AJAX and adhering to the same origin policy

I recently came across a Chrome extension called Postman that has proven to be incredibly useful. This tool is particularly handy for those working with RESTful applications. One thing that has puzzled me is how Postman is able to successfully send POST r ...

Issue with Material-UI DataGrid Component: Unable to access property 'length' as it is undefined

I need to display my JavaScript Object Data in a table format with pagination and sorting capabilities. I have chosen the DataGrid component from Material UI, but I am encountering some errors. Below is the code snippet: import React from 'react&apos ...

Uploading files into an array using Angular 2

Struggling to incorporate an uploader within an array: I've got an array of users displayed in a table using "ng-repeat". I want to add a column with a button to upload an image for each user. Currently, I'm utilizing ng2-file-upload, but open t ...

Tips for resolving the error "Parsing near 'Unexpected end of JSON input while parsing...' for...'mocha':'^3.2.0','s'":

Once I've successfully set up react and react-dom, the next step is to install webpack. However, I encountered an error during this process. To troubleshoot, I decided to install babel-loader first to ensure that both npm and my internet connection a ...

Utilizing PHP and Ajax for paginating JSON responses

I have successfully parsed some JSON data from the YouTube API, but I am running into a limitation where only 50 results can be shown per request. I am looking for help on how to implement pagination using either JavaScript or Ajax in my PHP script. The go ...

Angular 4: Modifying the URL without the Component being Displayed

I'm currently facing an issue where I am attempting to link a component from one component using routerLink = "selected" const routes: Routes = [ { path: '', children: [ { path: 'account&apo ...

The functionality of ng-table appears to be compromised when working with JSON data

Currently, I am facing an issue while using a JSON file to populate data in my Angular ng-table. Even though the JSON data is being displayed in a regular table format, certain functionalities of ng-table like pagination and view limit are not functioning ...

Putting off the execution of a setTimeout()

I'm encountering difficulties with a piece of asynchronous JavaScript code designed to fetch values from a database using ajax. The objective is to reload a page once a list has been populated. To achieve this, I attempted to embed the following code ...

Retrieving device information through JavaScript, jQuery, or PHP

Looking to build a website that can identify the device name and model of visitors accessing the page from their devices. ...

A specialized identifier for nested objects in a React component

I am currently working with a JSON data structure that looks like this: [ [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ], [ { city: x patients: x id: 1 }, { city: y patients: y id: 2 } ...

Utilizing jQuery UI for Autocomplete Functionality with Objects

Currently, I am utilizing jQuery version 1.11.2 and attempting to implement the autocomplete widget to interpret a data array. The array consists of two individuals - Will Smith and Willem Dafoe. I anticipated that upon typing 'Wi' in the text fi ...

Tips for chaining actions in Javascript using ActionSequence, LegacyActionSequence, or a similar method

I encountered an error while attempting to execute this example, despite trying both ActionSequence and LegacyActionSequence. I am in search of the correct method to chain actions. My attempts to find a solution in resources such as https://seleniumhq.git ...

Ensure data accuracy by triggering the cache - implementing SWR hook in Next.js with TypeScript

I recently implemented the swr hook in my next.js app to take advantage of its caching and real-time updates, which has been incredibly beneficial for my project (a Facebook clone). However, I encountered a challenge. The issue arises when fetching public ...

Encounter an issue during npm installation of electron: "Error verifying the initial certificate."

I recently developed a new app directory and ran the command npm init. However, I encountered an issue while trying to install Electron with the following line of code: npm install electron --save-dev. The error message I received is as follows: > [em ...

Utilize Node.js to parse JSON data and append new nodes to the final output

When parsing a JSON object in Node.js, the resulting hierarchical object can be seen in the debugger: datap = object account1 = object name = "A" type = "1" account2 = object name = "B" type = "2" If we want to add ...

A problem has occurred in Next.js where FileReader is not recognized and is causing a Reference

Exploring the latest features of Next.js 13 with the /app directory, I encountered an issue while using the FileReader in a basic client-side component that manages an input form. Here is a brief overview of the code: "use client"; import React, ...

Storing the background color in a JavaScript variable

I've been experimenting with creating a fade in and out effect for a background image on a website. I've also been attempting to capture the background color of a div and store it in a variable. Here's what I have tried: elem = document.ge ...

Adding information to an array within a document in a MongoDB database

I am facing an issue where I am trying to add data to the readBook array in my User collection document. The code and console.log seem to indicate that the User is retrieved from the database and there is data to push, but nothing changes after the code ex ...