Iterating over an array and displaying elements on the webpage

Struggling to access an array and loop through it, but only able to print out one element instead of all. Need a hint on how to solve this issue.

See my code below:

let toppingsCount;
const burger = document.createElement('div');
const toppingsDiv = document.createElement('div');
const condiments = ['Ketchup', 'Mustard', 'Relish']
const condimentsNewDiv = document.createElement('div');

function createBurger(condiments){
    burger.className = 'burger';
    burger.appendChild(toppingsDiv)
    toppingsDiv.className = "toppings";
    condimentsNewDiv.className = "condiments";
    toppingsDiv.appendChild(condimentsNewDiv)
    for(let toppingsCount = 0; toppingsCount != condiments.length ; toppingsCount++){
        toppingsDiv.appendChild(condimentsNewDiv).textContent = condiments[toppingsCount];
        console.log(condimentsNewDiv);
    }

    console.log(burger);
    document.body.appendChild(burger)


}
createBurger(condiments);

Inserted a console.log(condimentsNewDiv); inside the loop to check each condiment. However, it repeated "Relish" 3 times instead of printing out all three elements as expected:

<div class="condiments">Ketchup</div>
<div class="condiments">Mustard</div>
<div class="condiments">Relish</div>

Answer №1

It appears that you may be relying on the condimentsNewDiv element repeatedly instead of generating a fresh div for each condiment. By doing so, you are essentially replacing the textContent with each iteration.

To address this issue, consider implementing the following approach:

let toppingsCount;
const burger = document.createElement('div');
const toppingsDiv = document.createElement('div');
const condiments = ['Ketchup', 'Mustard', 'Relish'];

function createBurger(condimentsList){
    burger.className = 'burger';
    toppingsDiv.className = "toppings";
    
    for(let toppingsCount = 0; toppingsCount != condimentsList.length ; toppingsCount++){
        const condimentsNewDiv = document.createElement('div');
        condimentsNewDiv.className = "condiments";
        
        toppingsDiv.appendChild(condimentsNewDiv).textContent = condimentsList[toppingsCount];
        console.log(condimentsNewDiv);
    }

     burger.appendChild(toppingsDiv);

    console.log(burger);
    document.body.appendChild(burger);


}
createBurger(condiments);

By creating a distinct div for each condiment, we avoid reusing the same element unnecessarily.

Answer №2

Check out this functional demo:

let findElementById = (id) => document.querySelector(`#${id}`);

let dataStorage = [{
  id : 1,
  name : "abc",
},
{
  id : 2,
  name : "some",
}];

function generateTemplate(array) {
  let htmlString = ``;
  for(let item of array){
    //creating dynamic html template 
    htmlString += `
      <div>
        <h2 id=${item.id}>${item.name}</h2>
      </div>
    `;
  }
  return htmlString;
}
//trigger when page loads
window.onload = () => findElementById("demo").innerHTML = generateTemplate(dataStorage);

let addNewElement = () => {
  const generatedId = Math.floor(Math.random() * 100);
 //add new data entry
  dataStorage.push({
    id : generatedId,
    name : `newest element ${generatedId}`
  });
 
  //update the DOM by recreating the template
   findElementById("demo").innerHTML = generateTemplate(dataStorage);
}
<button onclick="addNewElement()">Add one more element</button>;

<div id="demo"></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

Change the input value by clicking different buttons

Looking for a way to change the value or source of an input when clicking on different buttons? For example, clicking on Button 1 changes the input to "apple" and Button 2 changes it to "orange", etc. Here is a snippet of what I have tried so far: $(doc ...

What is the best way to extend the functionality of npm script with command line arguments

After defining multiple scripts in my package.json file, I encountered an issue when attempting to run the $ npm run lint:fix command. The argument --fix did not get passed down to ./node_modules/.bin/standard, resulting in an error. { "name": "project" ...

The MongoDB regex is failing to provide the expected outcome

I'm facing an issue with searching data in MongoDB. I have a table with approximately 5000 entries of data that need to be searched based on multiple columns with specific priority criteria. The first priorities for the search are symbol, name, co_nam ...

Accessing information from a database table using Highchart and Ruby on Rails (ROR

I have a Ruby on Rails application that utilizes highcharts. I am currently working on enhancing it to display the amount of time spent on specific projects. To demonstrate what I am trying to achieve, I have created a JSFiddle example which can be found h ...

What is the most effective method for obtaining only the "steamid" from an AJAX request (or any other method)?

I have been attempting to extract only the "steamid" from an AJAX link without success. Could someone please provide some assistance? Here is the link to find and retrieve only the "steamid": here This is the code I have tried: var xhttp = new XMLHt ...

Choosing the initial offspring of an element that do not share a common parent

My question might not be perfectly phrased, for which I apologize. Is there a CSS method to select only the first child of an element without affecting others that are not grouped under the same parent? For instance: <div class="parent"> <div ...

The function Waterline.create() is not available

Currently in the process of building a basic REST API using Sails.js and Waterline-ORM, I've encountered an issue regarding Post.create is not a function when trying to create an object within the ORM on a Post request. Here is my model: module.expor ...

Spontaneous Link with JQuery and Colorbox

Just to clarify, I have no programming experience so please explain everything in simple terms. I am currently using a .js script within SharePoint and it's working perfectly! <!DOCTYPE html> <html> <head> <meta charset= ...

Tips for developing a dynamic game that adjusts to different screen sizes using Phaser 3

Recently, I've been on the hunt for a way to ensure my game adapts seamlessly to various screen resolutions when using Phaser 3. In the past, I achieved this with ease in Construct 2. However, I'm now curious to explore how best to implement thi ...

If there is data in MySQL, proceed to display the results on the page; if not, display a check

I am struggling to implement a small logic that I can't seem to figure out here. My goal is to retrieve MySQL data from the database and echo it on a .php file. Before doing so, I need to check if the data is available. If it is, then I want to proce ...

Store the visible image location in memory to be used across various sections

I'm currently developing a website with a scrolling background image feature. However, whenever I navigate to another page on the site, the animation restarts from the beginning. Is there a way to cache the position so that the animation continues sea ...

When the screen is resized, the embedded iframe moves smoothly to the left side

I recently created a projects page, but I am facing an issue with the iframe embed. Whenever the screen is resized, it keeps shifting to the left. However, what I really want is for it to be centered instead of being on the left side: https://i.stack.imgu ...

Is there a way to implement a scrollbar that only scrolls through one specific column in an HTML table?

I need help adding a scrollbar to a specific column in an HTML table. Take a look at this scenario https://jsfiddle.net/6wpdc4tL/: https://i.stack.imgur.com/svzIg.png This table should have two scrollbars, one for the light blue SCROLL column and another ...

Warning: The core schema has detected an unknown property `color` for the component or system `undefined` in Aframe + Vuejs. This issue was flagged within 10 milliseconds in

I am facing some challenges trying to integrate Aframe and vuejs seamlessly, as the console is displaying warning messages. It seems like Aframe is validating the attribute values before vue has a chance to modify them. Warning messages core:schema:warn ...

Variations in CSS Stylesheets for Various Parts of the Body

Currently, I am in the process of creating a single page website. One issue that I have encountered is needing a Bootstrap "modal" class popup to appear when a button is clicked. However, the template I am utilizing was designed using Bootstrap Version 1, ...

Using an array of JSON objects to set up a Backbone.js bootstrap-initialized application

Trying to bootstrap a backbone collection by using an array of JSON objects has led to some unexpected errors. When attempting to call reset on the collection object, an error from Backbone is thrown - Uncaught TypeError: undefined is not a function. Inte ...

How to showcase an image with Angular 2?

Just starting out with Angular 2 and ran into an issue while trying to display an image using a relative path. <img src="./../images/publicVideo1.PNG"> Unfortunately, I encountered the following error: null:1 GET http://localhost:4200/null 404 (No ...

Within a div element, there are links that I would like to hover over to emphasize the text

Hey there, I'm looking to make the text change color when you hover over the entire div. Currently, only the background changes color, but I want the text to as well. Thank you for your assistance! .shadow-box .service-box {text-align:center;borde ...

Run code once the Firestore get method has completed its execution

Is it possible to execute code after the get method is finished in JavaScript, similar to how it can be done in Java (Android)? Below is an example of my code: mColRef.get().then(function(querySnapshot){ querySnapshot.forEach(function(doc) { ...

rendering google charts using jade template

I am facing an issue while trying to display a google annotated chart on my jade project. I managed to successfully load a pie chart, but I am having trouble rendering a chart that requires the container element size to be explicitly defined. You can find ...