What is the best way to iterate through a list of element ids within an array and assign each one to a unique

I am currently in the process of restructuring my window.onload function to eliminate redundancy. My goal is to iterate through the elements I'm assigning to global variables using their ids. Initially, I successfully assigned onclick functions with a loop, but now I am unable to replicate this in a fiddle. The primary challenge lies in attempting to accomplish this task (view fiddle):

var gragh, gorgh;
var ids = ["gragh", "gorgh"];
for (var i = 0; i < ids.length; i++) {
    ids[i] = document.getElementById(ids[i]);  
    // TypeError: document.getElementById(ids[i]).onclick = doStuff;
}
//console.log(gragh);  undefined

The intention here is to assign the variables gragh and gorgh to p elements that share the same ids. While within the loop, ids[i] appears to reference the p elements. Yet, once outside the loop, these variables are undefined. This method also fails when iterating through an array without utilizing quotes around these variables. I even experimented with eval(), yielding mixed outcomes. Therefore, my question remains, how can I make this work? Additionally, why is this approach ineffective? Assuming ids = [gragh, gorgh] (minus the quotes), what do these variables represent within the array?

Answer №1

Avoid reassigning it within the loop, consider using a fresh array for population instead. View it as a pointer - you are altering it while iterating.

var gragh, gorgh;
var ids = ["gragh", "gorgh"];
var newSet = [];
for (var i = 0; i < ids.length; i++) {
    newSet[i] = document.getElementById(ids[i]);  
}

Answer №2

By the time the onclick function is executed, the loop will have already finished looping. Therefore, the value of i at that point will be the upper limit of the loop.

A possible solution to this issue is to use a closure.

var gragh;
var ids = ["gragh", "gorgh"];
for (var i=0; i<ids.length; i++) {
    (function(i){ // creating closure
  console.log(i)
    document.getElementById(ids[i]).onclick = doStuff
})(i) // passing value of i
}

document.getElementById("gragh").innerHTML = "ids[0]: " + ids[0] + ", ids[1]: " + ids[1]

function doStuff() {
  document.getElementById("gorgh").innerHTML = "ids[0]: " + ids[0] + ",ids[1]: " + ids[1] + ", var gragh: " + gragh;
}

gragh is undefined since you have only declared it but never initialized it.

JSFIDDLE

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

Encountering an issue where props are receiving a value of undefined within a component that is

After receiving a JSON response from getStaticProps, I double-checked the data by logging it in getStaticProps. The fetch functionality is working smoothly as I am successfully retrieving the expected response from the API. import Layout from '../comp ...

Utilizing jQuery callback parameters for interacting with PHP functions via AJAX

I am facing issues with AJAX results when using jQuery. Below are the functions I have defined: <script> function hello(callback, funct, val) { var ret = 0; console.log(val); $.ajax({ type: 'GET', ...

Retrieve the file using React and receive it through Express

Despite trying several solutions on SO, none have been successful for me thus far, so I kindly ask for your patience. In React front-end, the user initiates a file download request with some variables to the backend: const data = text.value; fetch(" ...

Adding numbered paths to a foreach loop results in transforming a single-dimensional array into a multi-dimensional array

I have developed a function to transform a single dimension array (adjacency list) into a multi-dimensional array. My goal is to include an enumerated path in $aCat. Input (single dimension) [2] => Array ( [id] => 2 [parent_id] ...

Form validation using ajaxSubmit with a pop-up to display a "processing" div

Currently, I have set up ajaxSubmit on my web form. Along with this functionality, I want to implement a pop-up div that displays a message saying "Processing the request" along with a dimmed background when the user clicks on the submit button. This is t ...

Conundrum encountered: SIGTRAP causing Electron failure to initialize

Exploring Electron for creating desktop applications has been my recent endeavor. However, I encountered this pesky error: /home/me/dev/my-electron-app-2/node_modules/electron/dist/electron exited with signal SIGTRAP Since the path leads to a binary file, ...

Utilizing various lodash filters in React for enhanced data manipulation

In my code, there is a function that filters a large set of objects based on specified inputs. The code snippet for this filtering function looks like this: filterLocations(filters) { let filteredLocations = _.filter( this.state.locations, locat ...

What could be the root cause behind this Selenium mistake?

My goal is to verify the correct scroll position in the browser using NightwatchJS and Selenium. Below is the command I am using in Nightwatch: assertScrollPosition(testValue) { this.api.execute(() => { const offsetValue = w ...

Sending data from an external input field to a form using AngularJS programmatically with element name

I am facing a challenge where I need to include an Input element in a Form, even though the Input is located outside of the form. While I have managed to add the input using form.$addControl(outerInput), it is not producing the desired outcome as shown in ...

Is there a way to deactivate the <script> tag using CSS specifically for media queries?

When designing a website exclusively for desktop usage, I encountered the issue of it not being viewable on mobile devices. I attempted to address this problem by utilizing the code below: script { display: none; pointer-events: none; } Unfortunat ...

What is causing the links I have inserted into the DOM using JavaScript to be unresponsive?

Currently, I am in the process of developing a Bookmarklet that will modify the functionality of the Google homepage. One feature that really stands out to me is the visual search page preview option - it's truly amazing! However, I have an idea to en ...

Provide personalized files according to individual preferences

I am looking to create a website that can generate a custom file based on user input. For example, if it's a story, I want the user's name to be inserted into the text where there is a designated variable for swapping, but this customization shou ...

What is the correct way to align text in jsPDF?

I'm currently encountering an issue with the jsPDF library. Although PDF generation works fine, I am struggling to justify text properly. The align: 'justify' attribute seems to function the same as align: 'left', and setting a spe ...

No JSON data detected in Typescript application

My Purchase class is fairly simple: export class Purchase { customer!: Customer; shippingAddress!: Address; billingAddress!: Address; order!: Order; orderItems!: OrderItem[]; } I have a checkout component that performs the following ac ...

Error encountered: Unexpected identifier in Reactjs code

I created a new application using create-react-app and encountered an Uncaught SyntaxError: Unexpected identifier for this particular line: import React, { Component } from 'react'; within the file public/scripts/app.js: 'use strict' ...

Identifying issues in jQuery code - What could be causing this error?

My jQuery code is not responding at all, not even showing an error! I'm not sure why, but here is the jQuery Code I'm using: /* This part is working fine */ $(".add-blog .blog-add-form .add-article .input-group select").on("change", function() ...

A wide array of possibilities can be explored using booleans, arrays, and the exclusion of typing

Trying to create a program based on 8 boolean statements. Created an array like this: array = [0,0,0,0,0,0,0,0];. Need the program to output different text for each combination. To simplify, will remove possibilities with less than 3 true statements. For ...

Modifying computed object in Vue: A step-by-step guide

My issue involves a simple selection of months: <select v-model="month" v-on:change="dateChanged('month', month)"> <option v-for="(month, index) in months" :value="index">{{ month }}</option> </select> The primary da ...

Is there a way to postpone the rendering of the page until all Vue variables have been flushed?

Incorporating vue.js into my project, I am utilizing bound variables for display. The structure of my webpage is as follows: <body> <!-- the content of the page, including an instance of the variable {{hello}} --> <script src="vue.js&qu ...

The AJAX Modal Popup Extender is not being displayed due to an error with the undefined Sys

My ASP.Net WebForms project, developed using C# in Visual Studio 2013, involves the utilization of an AJAX Popup Extender. I have integrated AjaxControlToolKit and AjaxControlToolkitStaticResources through NuGet. However, recently the popup form has ceased ...