Iterate through an array to dynamically assign values to variables using string elements

I'm facing a challenge here. I need to generate 4 new elements with the same class but different IDs without repeating code. Unfortunately, my loop doesn't seem to be working as expected.

I've spent the last 2 hours trying to crack this puzzle (even did a lot of Google research), inspecting elements using console.log, and printing them within the loop. At one point, I had to resort to console.dir to check the attributes of the created [object HTMLDivElement].

The script I have looks like this:

columnsArray = ["first", "second", "third", "fourth"]
for (var i = 0; i < columnsArray.length; i++ ) {
    let name = columnsArray[i]
    name = document.createElement("div");
    name.className = "container"
    name.setAttribute("id", name.name)
    document.querySelector("#board" + boardId).appendChild(name);
}

I'm wondering if there's a more straightforward way (worth attempting) to achieve my goal? Apart from the following workaround:

let first = document.createElement("div");
let second = document.createElement("div");
let third = document.createElement("div");
let fourth = document.createElement("div");

first.className = "container"
second.className = "container"
third.className = "container"
fourth.className = "container"

first.setAttribute = "first"
second.setAttribute = "second"
third.setAttribute = "third"
fourth.setAttribute = "fourth"


document.querySelector("#board" + boardId).appendChild(first);
document.querySelector("#board" + boardId).appendChild(second);
document.querySelector("#board" + boardId).appendChild(third);
document.querySelector("#board" + boardId).appendChild(fourth);

Appreciate any help in advance;)

Answer №1

You have inadvertently overridden the ID value from columnsArray within your loop by treating it as an element.

To avoid this issue, consider creating your element within a new variable:

columnsArray = ["first", "second", "third", "fourth"]

for (let i = 0; i < columnsArray.length; i++ ) {
    // Retrieve the ID value from the array
    let name = columnsArray[i];
    // Create a new element
    let elem = document.createElement("div");
    // Set its attribute to 'container'
    elem.className = "container"
    // Assign the ID value to columnsArray[i] (name)
    elem.setAttribute("id", name)
    // Append to board
    document.querySelector("#board" + boardId).appendChild(elem);
}

Answer №2

Your loop is functioning correctly, but you need to access the name in a different way than you initially thought.

To properly set the id, use the following code:

name.setAttribute("id", columnsArray[i])

The property name.name does not exist.

columnsArray = ["first", "second", "third", "fourth"];
boardId = 1;
for (var i = 0; i < columnsArray.length; i++ ) {
    let name = document.createElement("div");
    name.className = "container"
    
    name.setAttribute("id", columnsArray[i]) // setting name.id to columnsArray[i]
    
    name.innerHTML = "DIV id="+columnsArray[i]
    document.querySelector("#board" + boardId).appendChild(name);
    console.log(name, name.id)
}
<div id="board1"></div>

Answer №3

Instead of using

name.setAttribute("id", name.name)
, try using
name.setAttribute("id", columnsArray[i])

Next, follow these steps:

Replace the content with some information or element
name.innerHTML = columnsArray[i];
Append the name to the board by selecting it through document.querySelector("#board" + boardId).

Answer №4

try out this code block:

columnsArray = ["alpha", "beta", "gamma", "delta"]

for (i in columnsArray) {
  let label = columnsArray[i]
  label = document.createElement("div");
  label.className = "holder"
  label.setAttribute("id",columnsArray[i])
  document.getElementById('containerId').appendChild(label);
}

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

Preventing CORS problems when a web application imports JavaScript modules from different domains

Currently, I am in the process of developing a web application using NodeJS. The application is divided into a back-end responsible for handling database queries with MongoDB, and a front end built on a Node-based web server that utilizes interactjs alongs ...

Combine the entities within the object

I need to combine two objects that contain other objects within them, similar to the following structure: let selections = { 123: { abc: {name: 'abc'}, def: {name: 'def'} }, 456: { ghi: {name: ' ...

The issue arises when Node.js fails to identify the input fields that were dynamically inserted into the form

I came across a question similar to mine, but I found it challenging to apply the solution to node js. In my project, users can add items to a cart by clicking on them, which are then dynamically added to a form using jquery. However, upon submission, only ...

Implement a function that attaches an event listener to generate a new table row dynamically

I am currently facing an issue with my table that has ajax call functionality to add rows within the tbody element. The table is already set up on the html page. <table id='mytable'> <thead> <tr> <th>First Col</th> & ...

Ways to extract a number that comes after a specific word in a URL

I have a URL and need to extract a specific value from it by removing a certain step. I am looking for a regex solution to accomplish this task For example, if I have the window.location.href, the URL might look like this: https://mypage/route/step-1/mor ...

Issue with the functionality of socket.io callback functions

Previously, I used to utilize the socket.io emit callback in the following manner: On the client side: mysocket.emit('helloworld', 'helloworld', function(param){ console.log(param); }); On the server side: var server = r ...

The Vue instance methods provide a way to access and manipulate formatted properties

I am looking to implement a method that will generate the appropriate email format to be used as the href value in an anchor tag. This method should return the formatted string in the following format: "mailto:[email protected]". var facultyInformat ...

The React.js component search test encounters errors in locating components

I have been working on a React app that utilizes Redux and React-router. I am currently writing tests using React TestUtils, and I encountered an issue with the following test results: The first expect statement is successful: expect(nav).to.have.length(1) ...

What could be causing the issue with the variable appearing as undefined in

My class has a property: public requestLoadPersonal: Personal[] = []; As well as a method: private filterByGender(selectedValue: any): void { console.log(this.requestLoadPersonal); this.requestLoadPersonal = this.requestLoadPersonal.filter( ...

Angular 2 template format standard

Every Angular 2 example I encounter seems to place the template within the component decorator. import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: '<h1>Hello world</h1>' }) e ...

Using nodeJS to showcase content on a web page

I'm relatively new to NodeJS, and I am trying to figure out if there is a way to utilize NodeJS similar to JavaScript. My goal is to retrieve data from a database and display it within a div on my index.html page. When attempting to use querySelector, ...

PHP code snippet: Calculate the total sum of elements within an array

Here is an example of the array structure: array(2)( ['id'] => "59898441545", ['total'] => array( [0] => 2, [1] => 5 [2] => 10 [3] => 35 ) ); My goal is to transform the 'total' key from an array into the ...

Vue.js problem with conditional rendering using v-if

I'm struggling to grasp the concept behind how v-if functions. My goal is to dynamically hide buttons in the navigation bar based on the user's authentication status and current page. Specifically, I want the "My Account" button to be displayed w ...

Failure to trigger jQuery.ajax success function on Windows XP operating system

Snippet: $.ajax({ type: "POST", url: "students/login", data:{"data[Student][email]":_email,"data[Student][password]":_password}, beforeSend: function(){ $("#confirm").text(""); }, error: function (xhr, status) { ale ...

Iterate over the JSON data and evaluate the timestamps for comparison

I am attempting to iterate through this JSON data and compare the "start_time" and "end_time" values to ensure that there are no overlaps. However, I am struggling to implement this functionality. While researching, I came across a resource on how to vali ...

Adjusting the configuration of a PHP array

This issue is puzzling me more than I expected. I am trying to transform the following array structure: array:3 [▼ "subject" => array:2 [▼ 0 => "math" 1 => "english" ] "grade" => array:2 [▼ 0 => "a" 1 ...

Is there a method to generate an endless carousel effect?

Hello, I am trying to create an infinite carousel effect for my images. Currently, I have a method that involves restarting the image carousel when it reaches the end by using the code snippet progress = (progress <= 0) ? 100 : 0;. However, I don't ...

Angular filter within a nested ng-repeat loop

I've encountered an issue with nested filtering in Angular, where two filters are dependent on each other. What I'm trying to achieve is the following: <div ng-repeat="g in groups | filter:groupFilter"> ... <tr ng-repeat="c in g.co ...

The communication between the extension and chrome.runtime.connect() fails, possibly due to an issue with the chrome manifest version

I've been working on converting a Chrome extension that stopped functioning in manifest version 2. I've removed inline JavaScript and switched from chrome.extension.connect to chrome.runtime.connect. However, I'm still encountering issues wi ...

problem decoding json data from external server

I have a custom Grease Monkey script that is responsible for collecting data from a game and sending it to my server for tracking our team's progress. This process involves multiple Ajax requests between the GM script and the game, followed by sending ...