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

Image Blob increases over 50 times its original size when uploaded

I'm completely baffled by the situation unfolding here. Using Preprocess.js, I am resizing/compressing an image on the front-end. During the processfile() function on the image.onload (line 32), I convert the toDataURL() string to a Blob, in order to ...

What is the method for accessing font sizes through CSS code?

Why is the font size value in CSS returning incorrect values? Check out this jsFiddle example Here's the HTML code snippet: <div id="test">TEXT</div> <div id="test2">TEXT2</div> Now, take a look at the CSS: #test{ font ...

Transferring information between a pair of PHP functions via AJAX communications

Currently, I am tackling the challenge of user verification on our website. The process involves prompting users to input their credentials, click on the "send confirmation" button, receiving a code through SMS or messenger, entering the code in a field, a ...

Exploring the fundamentals of Django with a touch of creativity in CSS

As a newcomer to Django, I am currently working on setting up a basic Django application. I have progressed to chapter 5 in the Django online book: Before delving into databases, my goal is to incorporate some simple CSS and JS directly into the applicat ...

Can JSF Ajax be used to update non-JSF components like plain HTML elements?

Is it feasible to make changes to sections of my webpage that are not JSF elements? For instance, can I modify a simple HTML <div> or should I enclose it in a JSF component? ...

What could be causing the dysfunction of the jQuery class adding function?

I'm new to using jQuery and I'm trying to add a class to the 'a' tag when the 'li' tag is clicked. However, it doesn't seem to be working as expected. $('.nav-item').click( function() { $(".nav-item a").re ...

Having trouble getting a DIV to appear on top of another DIV containing an image

I need help with positioning an "InfoBox" above the main header image on my website. Despite trying z-indexes and adjusting position, I can't seem to get it right. If anyone has any suggestions, please share. Thank you! For reference, here is the HTM ...

How do I incorporate global typings when adding type definitions to an npm module?

Suppose I create a node module called m. Later on, I decide to enhance it with Typescript typings. Luckily, the module only exports a single function, so the m.d.ts file is as follows: /// <reference path="./typings/globals/node/index.d.ts" /> decl ...

Activate browser scrollbar functionality

Below is the HTML code snippet: <html> <head> <style> #parent { position : absolute; width : 500px; height : 500px; } #top { position : absolute; width : 100%; height: 100%; z-index : 5; } #bottom { position : absolute; width : 100%; ...

AngularJS ui-select not responding correctly to selected items

Currently, I am utilizing the ui-select module within AngularJS. <ui-select ng-model="tipData.category" search-enabled="false" name="category" required="required" class="orange-site-color-select custom-select"> <ui-select-match><span clas ...

Is the 'Document' term not recognized within expressjs?

I'm having trouble implementing a query selector in an ExpressJS application and it's not working // search products router.post('/search', function(req, res) { var db = req.db; var elasticlunr = require(&apo ...

submitting URL from dropdown menu without using the 'submit' button

My situation involves a dropdown list: @Html.DropDownList("InnerId", Model.GroupDropDownList, new { @class = "select_change" }) I am looking to achieve submitting the value when a user clicks on the selection without needing to select and then use a subm ...

Automatically modify browser configurations to disable document caching

Is it possible to prevent browsers from caching pages using JavaScript? I've noticed that even though PHP has a redirection implemented once the user logs in, when they press the browser's history button, it goes back to the login form. This is b ...

How can I remove specific items from a session array when they are selected?

I am seeking a solution that will allow me to remove a specific item from an array when that item is clicked. For example, if I click on "Two", it should disappear. See a demonstration here: CODE: <form method="post"> <input type="text" i ...

Utilize $stateParams to dynamically generate a title

When I click a link to our 'count' page, I can pass a router parameter with the following code: $state.go('count', {targetName: object.name}) The router is set up to recognize this parameter in the URL: url: '/count/:targetName& ...

Guide on implementing various styles for a class in Tailwind CSS when transitioning to dark mode with the help of Next.js 13.4 and next-theme

Is it possible to apply unique styles for a class in Tailwind CSS when transitioning to dark mode using Next.js 13.4 and next-theme? I am currently setting up a dark theme in Tailwind CSS with Next.js 13.4 utilizing next-theme. Within my globals.css file, ...

The nodes on a 2-dimensional grid overlap each other when the browser window is resized

In my project, I have set up a grid with 24 rows and 64 columns, totaling to 24x64 nodes. However, I am facing an issue where the nodes overlap when I open the console window. I am looking for a solution to automatically resize all nodes based on changes ...

Changing the Month Label Format from Short (MMM) to Long (MMMM) in Angular Material Datepicker

I am looking to customize the month labels in Angular Material datepicker. By default, the month view displays in MMM format and I want to change it to MMMM using custom MatDateFormats. export const APP_DATE_FORMATS: MatDateFormats = { parse: { dat ...

Is there a way for me to scroll and bring the block up to the header when the button is clicked?

My goal is to create a functionality where clicking on the button with the class .booking__button will smoothly scroll the block up under the header. The position of the block should remain consistent, only the scrolling effect should be visible to the use ...

Organize images with overlays to the center of the page

I need help centering a group of pictures (a 3x3 table) on my webpage. I was able to center them before adding image overlays, but now the images are showing up in the top left corner of the page. How can I group and center them, and how do I specify the i ...