Utilize the ID attribute for naming arrays in jQuery

We have multiple links enclosed in a block:

<div>
    <a href="#" id="john">text</a>
    <a href="#" id="mary">text</a>
    <a href="#" id="emma">text</a>
</div>

Each link has a unique id.

I am attempting to create separate arrays in javascript for each link inside this block. The challenge lies in the dynamic nature of the ids, which change constantly.

The desired output should be like this:

var john = [];
var mary = [];
var emma = [];

The id of the link corresponds to the name of the new array.

1) How can I achieve this coding task?

2) How can I use the id of the link to reference an array? For instance, after creating the arrays, in javascript I want to do something like

$(this).attr("id").push("text"); // when hovering over a link

This code snippet does not work as intended. What is the correct method to accomplish this?

Answer №1

One cannot dynamically generate variables, however one can dynamically assign properties to an object. To do this, create a main object specifically for this purpose:

var mainObject = {};
$('a').each(function () {
    mainObject[this.id] = [];
});

To add elements to the array, use the following method:

mainObject[this.id].push('text');

Answer №2

If for some unknown reason you find the need to store data in separate arrays, you can achieve this by utilizing javascript's eval() function to create the arrays (and any other elements) dynamically.


$(document).ready(function(){
  $("a").each(function(){
    eval("var " + $(this).attr("id") + " = new Array()")
  })
})

You can then use eval similarly to push items into these dynamically created arrays.

However, I personally agree with Box9's approach as a more logical solution.

For further reference:

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

How can you extract elements from a JSON array into separate variables based on a specific property value within each element?

In the following JSON array, each item has a category property that determines its grouping. I need to split this array into separate JSON arrays based on the category property of each item. The goal is to extract all items with the category set to person ...

Combining JSON objects in Node.js

I am extracting data from my database and converting it to JSON format. However, I now want to merge all the JSON data into a single JSON object. I have attempted various methods, but due to my limited knowledge of JavaScript syntax, I have not been able ...

Uploading images seamlessly through ajax

Despite the abundance of tutorials, I am struggling to make them work. In my input form for file upload, I have: <input onChange="userPreviewImage(this)" type="file" accept="image/*" style="display:none"/> Here is my Javascript code: function use ...

The onkeyup event appears to be malfunctioning

onkeypress seems to be working fine, but I'm having trouble getting onkeyup to work. Any suggestions on how to make onkeyup work properly? https://jsfiddle.net/btykt0nk/ function isNumber(number_check) { number_check = (number_check) ? number_ ...

Unable to activate the WebRTC track event

As a novice in the realm of WebRTC, I ventured into creating peer connections between two browser windows. Utilizing a simple WebSocket server in Node.js running locally, everything seemed to be in order until the process of exchanging candidates. Unfortun ...

Using CSS to layer a background image

Let's explore combining multiple layers as background images using HTML5 and CSS3: <div style="background-image: url(layer1.png)">...</div> To add the next layer, we can use the following CSS code: div { background-image: url('la ...

What is the reasoning behind certain libraries offering methods that perform identical tasks, but one in synchronous and the other in asynchronous context?

It's common for libraries to provide two methods that perform the same task, with one running asynchronously and the other synchronously. For example, unlink in fs/promises is similar to unlinkSync in fs; also, compare, compareSync, hash, and hashSyn ...

No animation will be applied to slideUp() on a specific block without using jQuery

I'm having an issue with a simple animation using jQuery and the jQuery Easing plugin. The animations work fine, except when applied to section.quickReply Below is my HTML: <section class="post quickReply"> <form method="POST> ...

Adding an object to an ArrayList: A step-by-step guide

I'm encountering issues with adding objects to the list. I have a list of floors, each floor containing rooms. I can successfully add a floor, but I'm unsure how to add rooms to the floor list. I've attempted to access floor[index] or id, b ...

The function for fetching JSON data using AJAX is not functioning properly

Can someone help me troubleshoot why my code isn't working to retrieve a JSON file from a PHP page? Here is my PHP page: header('Content-type: application/json'); $jsonstart="{'files' : ["; $jsonend="]}"; $content="{'fir ...

"Enhance your web development skills by mastering jQuery alongside the

It's curious that jQuery doesn't support the use of the "+" sign. You can see how it functions with "1" and "3", but not with "2+". Just hover your mouse over each div to experience it. <div id="div-2+"></div> JSFiddle $('a. ...

Exploring the functionality of AngularJS routing on a webpage

Testing the routing functionality of AngularJS while creating a web page. The index.html will contain links to Home, Courses, and Students. Clicking on each link will load its respective HTML using AngularJS routing. The student information is stored in ...

What is the best way to retrieve the content within a <span> tag using jQuery?

Is there a way to extract the text 'This is my name' from within the span element? <div id='item1'> <span>This is my name</span> </div> ...

Unique color selection for progress bars in Bootstrap Vue

Can the color of a progress bar be customized to any specific value in hexadecimal format? The preset colors like 'success' or 'danger' are not meeting our requirements, so I need to define my own color for the progress bar using a hex ...

Utilize AJAX to fetch and load JSON data for use in a different function

When a button is triggered, I have two functions that run. One function is called immediately, while the other is called once the processing triggered by the button is complete. I want to optimize the loading time by loading the JSON data from the AJAX req ...

transforming unicode into regular characters prior to being presented on a webpage

I am currently utilizing the openinviter class to import contacts from emails. Sadly, it is showing Unicodes of non-English characters, like Polish, such as u0117 (and similar code types), instead of regular characters. Is there a way to convert these Unic ...

Google Chrome's development tools are unable to detect the manifest

I have a file named manifest.json, and I included it in my HTML using <link rel="manifest" href="./manifest.json">. Despite everything seeming correct, Chrome developer tools are unable to detect my manifest file! This is the content of my manifest ...

Retrieving data from an anonymous function in AngularJS and outputting it as JSON or another value

Within the following code, I am utilizing a server method called "getUserNames()" that returns a JSON and then assigning it to the main.teamMembers variable. There is also a viewAll button included in a report that I am constructing, which triggers the met ...

How to apply an active class to the current hyperlink in ASP.NET using C#

I am attempting to highlight the current active link using jQuery in an ASPX web form. First, I retrieved all hyperlinks from my database to gallery.aspx using the following function in the code-behind: public string build_Gallery_Category() { string ...

Maintaining the integrity of items in a Bootstrap 4 Navbar and ensuring their center alignment

I am currently working on developing a mobile website using ReactJS and Bootstrap 4. One of the requirements is to create a Navbar with specific functionalities. Normal Normal Menu: https://i.sstatic.net/DXfIt.png Collapse Collapse Menu: https://i.ss ...