Embed an array within a div using JavaScript

I'm looking to make a small adjustment to this code, acknowledging that it's far from perfect. Instead of simply writing the array contents into a single div, I'd like to create a new div for each number in the array and then add it to the card container.

balls90 = [ '1', '2', '3', '4', '5', '6','7','8','9','10','11', '12', '13', '14', '15', '16','17','18','19','20','21', '22', '23', '24', '25', '26','27','28','29','30','31', '32', '33', '34', '35', '36','37','38','39','40','41', '42', '43', '44', '45', '46','47','48','49','50','51', '52', '53', '54', '55', '56','57','58','59','60','61', '62', '63', '64', '65', '66','67','68','69','70','71', '72', '73', '74', '75', '76','77','78','79','80','81', '82', '83', '84', '85', '86','87','88','89','90' ];

function getNumbers(){

    var player1 = new Array();

    balls90.sort( function() { return Math.random() - .25 } );

    for ( var i=1; i<=12; i++ ) {   
        player1.push(balls90[i]);
        document.getElementById("cardContainer").innerHTML+=(balls90[i]);
    }

}

Answer №1

One straightforward approach is to refrain from directly appending to the div and append to a variable instead, as shown below:

var html='';
for (var i=1; i<=12; i++) {
    html+='<div>'+balls90[i]+'</div>';
}
document.getElementById('cardContainer').innerHTML+= html;

Answer №2

If you want to avoid messy string concatenation, you can achieve the desired result easily by utilizing document.createElement("div") in conjunction with appendChild()

var div = document.createElement("div");
div.innerHTML = (balls90[i]);
cardContainer.appendChild(div);

Check out this jsfiddle example.

This approach will eliminate the need for complex string manipulation.

Answer №3

One way to achieve this is by using element.createChild() in conjunction with element.appendChild().

Answer №4

Give this a shot


var whole_list = "";
for(var j=0; j<balls90.length; ++j){
    whole_list = whole_list + balls90[j] + "<br>";
} 

$("#container").html(whole_list);

Answer №5

One way to dynamically generate a div is by using the code

var div = document.createElement('div')
. After that, you can attach the values from an array iteration to a newly created node with the code
var node = document.createTextNode(value[i])
. The next step would be to save the dynamically generated DOM element in a variable like `div`. This same process can be repeated for the dynamic node. Finally, you can link the node to the DOM element by using div.appendChild(node), and then add the entire element to its Parent Element.

Answer №6

document.getElementById("cardContainer").innerHTML += ('<div>'+balls90[i]+'</div>');

To display each number in a separate div, simply enclose each number within <div></div> tags.

Check out the code on jsFiddle: http://jsfiddle.net/UjsgY/

Answer №7

Is this how you want it?

numbersList = [];
for (var j=0;j<90;j++) numbersList[j]=(j+1);

function fetchNumbers(){
  var player2 = new Array();
  numbersList.sort( function() { return Math.random() - .25 } );
  var cardHolder = document.getElementById("cardContainer")
  var element;
  for ( var k=1; k<=12; k++ ) { 
    player2.push(numbersList[k]);
    element = document.createElement('div');
    element.innerHTML=numbersList[k];
    cardHolder.appendChild(element)
  }
}

Answer №8

It seems like you are trying to generate a div for each item in the array. Have you ever heard of using array.join()? In order to contain the elements, you will need a container. I can help by creating one and then generating individual divs using array.join().

var container = document.createElement('div');
//A string that includes multiple divs with Array elements.
container.innerHTML = '<div>' + balls90.join('</div><div>') + '</div>';  
//Appending the div to the end of the body to minimize DOM refreshes
document.body.appendChild( container ); 

Answer №9

// There are many different methods for achieving this, here's one more

let newDiv = document.createElement('div');
let textNode = document.createTextNode('1');
let counter = 1;
let tempContainer = document.createDocumentFragment();
newDiv.appendChild(textNode);
tempContainer.appendChild(newDiv);

while(counter < 90){
    let copyDiv = newDiv.cloneNode(true);
    copyDiv.firstChild.data = ++counter;
    tempContainer.appendChild(copyDiv);
}

document.getElementById("cardContainer").appendChild(tempContainer);

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

Did I accidentally overlook a tag for this stylish stripe mesh Gradient design?

I've been attempting to replicate the striped animated Gradient mesh using whatamesh.vercel.app. I've set up the JS file, inserted all the gist code into it, and placed everything in the correct locations, but unfortunately, it's not functio ...

Displaying items from an array is made easy thanks to the combination of mapGetters, VUEJS, vuex, and vuetify

My website has two main routes: one for the home page and another for a configuration panel. In the home page, there is a container displaying information such as date, time, current temperature, etc. Below that, there is another container where users can ...

Are there alternative methods for handling routes in React, other than using the react-router-dom@latest library?

Currently, I am focused on a frontend project. One of the tasks at hand is to configure the network of routes. During my research, I came across react-router-dom@latest as a potential solution. However, I am curious to explore alternative options availa ...

Utilizing Node.js callback for validating JWT tokens

In my Node.js server, I have set up an authentication route to authenticate requests: app.get('/loggedin', auth, function(req, res){ console.log(req.authenticated); res.send(req.authenticated ? req.authenticated: false) }) From what I u ...

Is there a way to ensure that a statement will not execute until the completion of a preceding function?

I am encountering an issue where the window.open function is being called too quickly, causing my other function not to finish and post in time within my onclick event. I attempted to address this by setting a timeout on the trackData() function, but it o ...

File handling in Angular 2 using Typescript involves understanding the fundamental syntax for managing files

Would someone be able to explain the fundamental syntax for reading and writing text files, also known as file handling in TypeScript? If there is a corresponding link that anyone could provide, it would be greatly appreciated. ...

Passport Authentication does not initiate a redirect

While working on a local-signup strategy, I encountered an issue where the authentication process against my empty collection was timing out after submitting the form. Despite calling passport.authenticate(), there were no redirects happening and the timeo ...

Assigning properties to the constructor using `this.prop`

Within a React class component, I have multiple methods and the component receives various props. I am contemplating whether I should assign each prop as this.propName in the constructor and then access them using this.propName. For your reference, below ...

Forbidden access error in codeigniter with Ajax request 403

I'm struggling to send a value via Ajax to a Controller file in Codeigniter, but unfortunately I haven't been successful. Despite researching this issue and finding that it has been asked many times before, I still can't seem to find a solut ...

Converting an Array into a String

Struggling to transfer a MYSQL associative array into a PHP array and encountering the following error: Error message: Array to String type conversion Code snippet: $sql="SELECT brand_id FROM brand WHERE (name IS NOT NULL OR name != '') AND ...

What is the best way to integrate database information into the array shown below?

Is there a way to populate the array with data from the database without any issues? I've attempted various methods but have been unsuccessful so far. I am looking to store database values in an array structure class topsis { public $alternatif = arr ...

Obtain documents from one folder, analyze files in a different location, and then correlate files with their respective contents

Let me clarify by giving an example - I have a directory with images and another one with text files containing image information. I want to create an array where each image is matched with its corresponding data in another array. I am feeling overwhelmed ...

Tips for transferring a value from a Next.js route to a physical component

So, I encountered some issues while creating a Next.js project related to the database. To solve this problem, I connected to Vercel's hosted database. After successfully inserting and selecting data into the database using routes, I wanted to enhance ...

Deciphering unidentified Json data

Having some trouble with an error in my note taker app built using expressjs. Everything was working fine until I tried to save a new note and it's throwing this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () Here&apos ...

Exploring the functionality of arrays within Selenium IDE

Recently delving into Selenium IDE, I am a beginner and looking for guidance. The challenge at hand: How can I access values from an array generated by execute script | var array1 = document.getElementsByClassName("Post"); return array1; | array1 Initi ...

Automatic Textbox Closer

Connected to this AngularJS issue on IE10+ where textarea with placeholder causes "Invalid argument." and also this AngularJS 1.1.5 problem in Internet Explorer with ng-show and objects (Bug), we had to resort to using the textarea element as a self-closin ...

Utilizing reactjs (MERN stack) to dynamically update content on a single page based on both URL parameters and database queries

Hello everyone, please excuse my English Imagine I have page1 with content in a database, and page2 with different content in another database. Both page1 and page2 share the same template, but I want to dynamically change the content based on the URL or ...

I'm trying to find a way to access a particular field within an HTML document using JavaScript in Node.js. Can anyone

<Response> <SMSMessageData> <Message>Delivered to 1/1 Total Cost: NGN 2.2000</Message> <Recipients> <Recipient> <number>+9109199282928</number> <cost>NGN 2.2000&l ...

Even though I am aware that the variable AJAX is attempting to return is not empty, it is still returning 'undefined'

I wrote a basic PHP script that retrieves information from a database and stores it in a multidimensional array: <?php //PHP code to fetch data from DB error_reporting(E_ALL); $db = new mysqli("localhost","root","pass", "Media") ...

Fetch Timeout Issue in React Native

I am currently using fetch to retrieve data from a server. Unfortunately, I am facing issues with setting a timeout for the fetch request in case the server does not respond. This is my global fetchData class: fetchGetResp(url, token) { return fetch( ...