Using a for loop to cycle through an array and generate sibling div elements

I'm attempting to display the content of the gameTwo array in two child divs under the game2 element. However, the issue I'm facing is that the loop creates a child of a child on the second iteration. Could someone provide guidance on how I can adjust this code to ensure that both divs are siblings?

var gameTwo = ['Kansas', 'Villanova']

var gameTwoText = '';
    for (i = 0; i < gameTwo.length; i++) {
        gameTwoText += "<div>" + gameTwo[i];
    }
var secondGame = document.getElementById('game2').innerHTML = gameTwoText;

Answer №1

Make sure to include a closing tag for each div element - like this:

gameTwoText += "<div>" + gameTwo[i] + "</div>";

If you don't add the </div>, the first div won't be properly closed and each subsequent one will be nested within the previous one.

Answer №2

To ensure proper execution, be sure to properly close the DIV tag within the loop. Alternatively, you can opt for a more traditional approach by dynamically creating the elements using the DOM:

var secondGame = document.getElementById('game2');
var gameTwo = ['Kansas', 'Villanova'];
var div = null;
for (var i = 0, len = gameTwo.length; i < len; i++) {
    div = document.createElement('div');
    div.appendChild(document.createTextNode(gameTwo[i]));
    secondGame.appendChild(div);
}

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 access to websites through a web application using JavaScript

I am in the process of creating a web application that enables users to create a list of websites they wish to block, preventing access from their browsers. My goal is to block websites on all browsers, but I have narrowed my focus to Chrome for now. I ha ...

Node.js HTTP request not returning any content in the body/message

Having some trouble with the requestjs package as I attempt to post data and receive a response. No matter what I do, the body response always ends up being undefined. const request = require('request'); request({ method: "POST", ...

steps for setting up babel-cli and babel-preset-react

I attempted various methods of installing babel-cli babel-preset-react Here's what I tried: npm install --save-dev babel-cli babel-preset-react However, when I run babel -h An error message appears saying The program 'babel' can be found ...

Retrieve the data from an HTTP Request using AngularJS

I've been working on creating a JavaScript function that sends an HTTP Request to retrieve data, but I'm struggling with how to handle and use the result in another function. Here are the two functions I've tried (both intended to achieve t ...

AngularJS ng-repeat with dynamic ng-model is a powerful feature that allows for

I am attempting to dynamically generate the ng-model directive within an ng-repeat, but I am encountering a browser error. Our goal is to dynamically retrieve attributes of a certain type and set them in the DOM. The specific error I am receiving is: Err ...

Ways to confirm the actual openness of Express app's connection to MongoDB?

I'm currently developing an Angular 7 application that utilizes MongoDB, Node.js, and Express. One issue I encountered is that if I start my Express app (using the npm start command) before connecting to MongoDB (using the mongod command), the Express ...

Convert a 3-dimensional Numpy array into a 2-dimensional array by taking only the outermost index

I have an array consisting of multiple 2-dimensional arrays, depicted as follows: +------+ +------+ | | | | | A | | B | | | | | +------+ +------+ My goal is to remove the outermost parentheses and combine the inne ...

Audio playback system in Node.js

I'm looking to create a seamless playlist of mp3 files that play one after the other. While it may seem straightforward, I'm facing challenges keeping the decoder and speaker channel open to stream new mp3 data in once a song finishes playing. Be ...

Turning a string array into a basic array can be achieved through a few simple steps

While I am aware that this question has been posed multiple times, my scenario is slightly unique. Despite exhausting numerous methods, I have yet to discover a suitable workaround. $array = ["9","8","7","6","5"]; //result of javascript JSON.stringify() ...

What is the best way to navigate to a new webpage after clicking a button?

Currently, I am experimenting with socket io and node to show two different HTML pages. Here's what I have set up: app.get("/", function(req, res) { res.sendFile(__dirname + "/login.html") }) The scenario involves a user logging in and pressing ...

add before the beginning and after the end

Hi there, I'm trying to figure out how to add before my initial variable and after my last one. This is the code snippet: $pagerT.find('span.page-number:first').append($previousT); $pagerT.find('span.page-number:last').append($n ...

Creating a form submission event through Asp.net code behind

Is there a way to change the onsubmit parameter of a form in an asp.net project, specifically from the master page code behind of a child page? I am interested in updating the form value so that it looks like this: <form id="form1" runat="server" onsu ...

Limiting click event to only Image component in Next.js

Is there a way to trigger a click event only on the image itself, rather than the entire parent div? When setting width and height for the parent div, the click event seems to encompass the entire area. For instance, if the image is 600 pixels wide by 300 ...

Utilizing React and Material-UI to Enhance Badge Functionality

I am exploring ways to display a badge icon when a component has attached notes. I have experimented with three different methods and interestingly, the results are consistent across all of them. Which approach do you think is the most efficient for achiev ...

How to Retrieve Nested Arrays from a Database Using Codeigniter

I need assistance with retrieving customer orders from my database and organizing them in an array format. The database consists of two tables: orders and order_items, which are connected by the order ID fields. public function getUserOrders($id) { $t ...

Can a variable's value be altered within an array?

I am in the process of developing a software where I encounter a scenario where I need to update the value of an integer that is stored within an array. Here's an example to illustrate my point: int num = 0; int[] nums = new int[] {num}; Console.Wri ...

What is the best method to retrieve the initial elements from an array before proceeding to fetch the subsequent ones?

I'm currently in the process of setting up my blog page on my website, and I have a posts folder containing markdown files for all my blogs. I'm trying to find a way to efficiently display these blogs on a single page by initially loading only th ...

Discovering a way to showcase every event a user is linked to, employing Fullcalendar Rails

Here is the current model structure: class User < ActiveRecord::Base has_and_belongs_to_many :event_series has_many :events, through: :event_series end class Event < ActiveRecord::Base belongs_to :event_series end class EventSeries < Activ ...

Form_Open will automatically submit - Ajax Submission in CodeIgniter

I am facing an issue with submitting my form via Ajax. Despite setting up a function to prevent the page from refreshing upon submission, it seems like the form still refreshes the page every time I click submit. I even tried creating a test function to lo ...

Combining Asynchronous and Synchronous Operations in a Function: Using Cache and Ajax Requests in JavaScript

I am currently exploring how to combine two different types of returns (async / sync) from a function that is structured like this : retrieveVideo(itemID){ let data = localStorage.getItem(itemID) if ( data ) { return data; } else{ axios.ge ...