A guide on transferring values from three separate arrays into a designated div using JavaScript

Imagine having 3 div elements and 3 different sets of arrays. The goal is to assign the values from each array into corresponding divs. How can this be achieved?

Take a look at my sample divs below:

<div id='001'><div id="nr001"><div id="clr001"></div></div></div>
<div id='002'><div id="nr002"><div id="clr002"></div></div></div>
<div id='003'><div id="nr003"><div id="clr003"></div></div></div>

Now, I have 3 sets of arrays obtained through JSON.parse() as shown below:

["001", "002", "003"],["8", "9", "20"], [ "brown", "black", "yellow"]

The Desired Outcome: The objective is to populate the divs with the respective values from the arrays like this:

<div id='001'>8<div id="nr001"><div id="clr001">brown</div></div></div>
<div id='002'>9<div id="nr002"><div id="clr002">black</div></div></div>
<div id='003'>20<div id="nr003"><div id="clr003">yellow</div></div></div>

Here's what I've attempted so far:

var str = xmlHttp.responseText;
var res = JSON.parse(str);

var set1 = res[0], set2 = res[1], set3 = res[3];
for (var i = 0; i < set1.length; i++) {
    var div1 =  document.getElementById("nr"+set1[i]);
    var div2 =  document.getElementById("clr"+set1[i]);
    if (div1) {
        div1.innerHTML = set2[i];     
    }

  if (div2) {
        div2.innerHTML = set3[i];     

    }
}

Only div2 seems to be populated, not div1. Perhaps more lines of script or a new approach are needed.

AFTER IMPLEMENTING THE SOLUTION:

I want to express my gratitude to everyone who provided a solution. It turns out that I failed to mention I used setTimeout() to recall the function every 15 seconds. So, other answers suggested appending the element? Does the result get appended to the previous one when another call finishes?

In the end, by assigning spans instead of using divs for both, the issue was resolved. Now, I am getting the desired output. Thank you to all contributors!

Answer №1

When dealing with nested divs, it's important to handle the content assignment carefully to avoid destroying the existing structure. An additional tag can help maintain the integrity of your layout:

<div id='002'><span id="abc002"></span><div id="nr002"><div id="clr002"></div></div></div>

var span =  document.getElementById("abc"+index1[j]);
var innerDiv =  document.getElementById("clr"+index1[j]);
if (span) {
    span.innerHTML = value2[j];     
}

if (innerDiv) {
    innerDiv.innerHTML = value3[j];     
}

Answer №2

Omer Hassan's answer has been slightly modified. In order to append data to the main div using its innerHTML, and then proceed to append data to the inner div, follow the code snippet below:

var res = [["001", "002", "003"],["8", "9", "20"], [ "brown", "black", "yellow"]];

for (var i = res[0].length - 1; i > -1; i--)
{
    var suffix = res[0][i];
    var div1 = document.getElementById("nr" + suffix);

    div1.innerHTML = res[1][i] + div1.innerHTML;   

    var div2 = document.getElementById("clr" + suffix);
    div2.innerHTML = res[2][i];
}

VIEW DEMO FIDDLE

Answer №3

const data = [["001", "002", "003"], ["8", "9", "20"], [ "brown", "black", "yellow"]];

for (let index = data[0].length - 1; index >= 0; index--) {
    let suffix = data[0][index];
    let container = document.getElementById(suffix);
    let div1 = document.getElementById("nr" + suffix);
    let div2 = document.getElementById("clr" + suffix);

    container.insertBefore(document.createTextNode(data[1][idx]),div1);
    div2.innerHTML = data[2][index];
}

Answer №4

What do you think of this approach?

let info = [["101", "102", "103"],["10", "11", "22"], ["red", "blue", "green"]];

for ( let j = 0; j < info[0].length; j++ ) {
    let item = document.getElementById(info[0][j]);
    item.innerHTML = info[1][j] + item.innerHTML;
    document.getElementById('color' + info[0][j]).innerHTML = info[2][j];  
}

By the way, I am assuming that the first array represents the IDs, hence the loop through them using info[0].length.

Check it out live @ JSFiddle and here as well.

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

What could be causing the "length" property of undefined error when attempting to install React-Bootstrap with the command "npm i react-bootstrap"?

Currently, I am working my way through a comprehensive MERN full-stack tutorial. So far, things have been going smoothly - I used the "npx create-react-app" command to set up the react application and everything is compiling and running perfectly. Howeve ...

Exports for Express Router Module/Functions

I am currently working on exporting a function and an express router from the same file. The function is intended to verify certificates, while the route is meant to be mounted on my main class for other routes to use. I want to encapsulate both functional ...

Incorporating search engine optimization into a React project

Currently, I am tackling a React js project and have been assigned the task of incorporating SEO into it. I have attempted to find some open source resources that outline a step-by-step process on integrating SEO, as well as how to implement tags and end ...

Adding a new row to an HTML table using JavaScript

In the code snippet below, I am facing an issue with adding a row to an HTML table and inserting it into a database. I have tried using JavaScript to add the row in order to avoid postback, but so far, I have been unsuccessful. Can someone assist me in t ...

Troubleshooting Issue with Post/Get Request in AJAX and Flask Framework

My current project involves building a YouTube scraper webpage purely for educational purposes. I have created a web page with a text box to enter search queries and a search button. When the button is clicked, an Ajax post request is sent with the text bo ...

Creating content by extracting key value pairs from a JSON object retrieved from Firebase

After setting up a Firebase database and populating it with JSON data, I found code from the Firebase documentation that allows me to update the data in real time. While this works well for my needs, I also want to access the values in the JSON to create l ...

Executing the JavaScript function on a batch of 6 IDs at once (should return every 6 calls?)

I'm curious if there's a function available that can group called data into sets of 6. Here's the expanded version of the code var currentResults; function init() { getProducts(); } function getProducts() { $.ajax({ url:" ...

Tips for maintaining space beneath an image when text wraps around it

.blogimgarea { width: 38%; padding-right: 26px; float:left; } img{max-width:100%} .blogtextarea { width:55%; padding:22px 32px 0 0; float:right; } <div class="newpostregion pt70"> <div class="blogimgarea"> <img class="featblogimg" src="https ...

React app frequently retrieves images from the server whenever react-router is being utilized

I am currently working on a create-react-app project that utilizes the react-router-dom. Within this project, I have several Components that function as pages in a Single Page Application. Each page includes the following component: return ( <im ...

Discovering the culprit causing a freeze on your page: Uncovering the tool or technique to identify the problematic

What is the best tool to identify resource-heavy or infinite loop JavaScript/jQuery scripts? I am currently experiencing issues with a specific template: When I open this page on Firefox 46.0.1, it freezes after a few minutes. I am having trouble pinpoin ...

Is the Sourcecode for the Raspberry Pi Cam with WebRTC and UV4l driver Closed?

I'm utilizing the UV4L driver (RasPiCam) from this link along with the WebRTC extension to achieve a continuous live view, streaming out via this HTTP server (RaspberryPi). I am interested in examining the source code being executed on the server. Is ...

Exploring the integration of react-leaflet with Nextjs: A step-by-step guide

Hello everyone, I'm currently facing an issue while trying to integrate a Leaflet map into my Next.js application. The error window is not defined keeps popping up and despite searching on stackoverflow, I haven't found a solution yet. The code ...

javascript utilizing key inputs

Is there a way I can create a function that activates when the "A" key on my keyboard is pressed, sending a signal to nupp('/TS'), and stops sending the signal when the "A" key is released? <html> <head> <script src=\"htt ...

The peculiar behavior of Google Maps markers refreshing inconsistently upon bounds adjustment

I recently completed a project involving a restaurant app using Vue and Google Maps. While everything is functional, I have encountered a persistent bug with the markers. When navigating on the map and the bounds change, some markers seem to disappear. Ev ...

Swap out The div element with the html() method

I'm encountering an issue when trying to swap out a div element with ajax. My goal is to create a start/stop button functionality. The page displays a list of card elements, each with its own button, which are stored in separate html files. work_orde ...

Swap out all hyperlinks on the webpage with a different URL

I am looking to update all links in a specific style with new ones. I want to streamline the download process for Google Drive links. https://drive.google.com/file/d/1cCIWJMBOX-NvzYVTQajaVo5lNknYA2E8/view?usp=sharing My plan is to extract '1cCIWJMBO ...

Guide to importing a Kotlin/JS generated module into a separate npm-dependent project

I am interested in developing a JavaScript library using Kotlin Multiplatform (such as the project found here, which includes a websocket server and a JavaScript client). My goal is to build this library as an npm package and then import it into my Vue pro ...

New issue with Express js 4x: receiving an empty object from :req.params

Having trouble fetching URL parameters in express js as the object is coming back empty. var password= require('./routes/password'); app.use('/reset/:token',password); password.js router.get('/', function(req, res, next) { ...

Updating a single document in Node JS using Express is a simple and straightforward process

I'm having trouble understanding why my documents aren't updating. When I retrieve any record and load it into the form using http://localhost:3000/update2?buyerID=2299, the field doesn't update when I make changes and click submit. It rema ...

Browse the string on the web browser

Is there a way for me to continuously read and capture a string as it is being written in the browser, retrieving its value every 5 seconds? I need to be able to monitor the changing value while it is being input. In PHP, I have the following code snippet ...