Loop through and display content on the webpage with a for loop

I'm attempting to create a loop that will display information in three different areas of the DOM. Essentially, I have an array of enemies and I want to randomly select three of them to display in separate HTML div classes (firstEnemy, secondEnemy, thirdEnemy). While I know I could manually assign the values like so:

 let loadEnemies = document.querySelector(".firstEnemy");
    loadEnemies.innerHTML = 
        '<p>Name: '+randomLowEnemy.name+'</p>' +
        '<p>Health: '+randomLowEnemy.health+'</p>'

repeating this process multiple times would be cumbersome, which is why I'm trying to implement a loop to automate it for me. Currently, I am able to select an enemy and display its information using:

let enemy;

function Enemy(rank, name, img, health, attack, speed){
    this.rank = rank;
    this.name = name;
    this.img = img;
    this.health = health;
    this.attack = attack;
    this.speed = speed;
};


//Ranks are E, C, D, B, A, S with corresponding numbers 1-6

let goblin = new Enemy(1,"Goblin", 50, 5, 10);
let centipede = new Enemy(2 ,"Giant Desert Centipede", 100, 15, 5);
let jackal = new Enemy(2, "Dungeon Jackal", 75, 10, 15);

const lowRankEnemies = [ goblin, centipede, jackal]; 
let randomLowEnemy = lowRankEnemies[Math.floor(Math.random() * lowRankEnemies.length)];

console.log(randomLowEnemy);

let loadLowEnemies = 3;
for(let i =0; i < loadLowEnemies; i++){
    let loadEnemies = document.querySelector(".firstEnemy");
    loadEnemies.innerHTML = 
        '<p>Name: '+randomLowEnemy.name+'</p>' +
        '<p>Health: '+randomLowEnemy.health+'</p>'
}

Answer №1

To ensure a random enemy selection within the loop, it is important to assign elements in a sequential manner.

By assigning all enemy DOM elements the common class enemy, instead of individual classes like

'.firstEnemy', '.secondEnemy', '.thirdEnemy'
, looping over them collectively becomes more efficient.

function Enemy(rank, name, img, health, attack, speed) {
  this.rank = rank;
  this.name = name;
  this.img = img;
  this.health = health;
  this.attack = attack;
  this.speed = speed;
};


//Ranking will go from E, C, D, B, A, S and follow 1, 2, 3, 4, 5, 6

let goblin = new Enemy(1, "Goblin", 50, 5, 10);
let centipede = new Enemy(2, "Giant Desert Centipede", 100, 15, 5);
let jackal = new Enemy(2, "Dungeon Jackal", 75, 10, 15);

const lowRankEnemies = [goblin, centipede, jackal];
document.querySelectorAll(".enemy").forEach((enemy) => {
    let randomLowEnemy = lowRankEnemies[Math.floor(Math.random() * lowRankEnemies.length)];
    enemy.innerHTML = 
        '<p>Name: '+randomLowEnemy.name+'</p>' +
        '<p>Health: '+randomLowEnemy.health+'</p>';
});
<div class="enemy"></div>
<div class="enemy"></div>
<div class="enemy"></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

What is the best way to implement sorting in a table using react virtualized?

I've been working on implementing sorting in my project using the table sorting demo available on Github. Here is the code I'm using: import React from 'react'; import PropTypes from 'prop-types'; import { Table, Column, Sor ...

Angular Application for Attaching Files to SOAP Service

I am currently utilizing soap services to pass XML data along with file attachments. While SoapUI tool works perfectly for this purpose, I want to achieve the same functionality through Angular6 in my project. Below is a snippet of my Xml code. <soap ...

Images on web pages are automatically resized to fit into a smaller preview window

Currently, I am facing an issue with the display of images in my grid windows on my website . The images are appearing as partial representations instead of rescaled versions where the whole picture is resized to fit the grid window. I have attempted mod ...

The feature in DataTables that allows users to choose how many items to display per page is not functioning correctly

My DataTable is experiencing issues with the box that allows you to select how many items per page you want to show. Instead of displaying just the numbers, it shows: [[5,10],[5,10]]. I have tried to troubleshoot this problem without any success. Addition ...

Tally each div individually and display the count within each div, instead of showing the total count across

I have come across various solutions that show the total number of certain special divs, such as: $('.someclass').length However, I am facing a different challenge. I want to sequentially count each div with a numerical sequence. For instance, ...

Is there a way to dynamically include an attribute using VueJS?

Is there a way in Vue to dynamically add an attribute, not just the value of an attribute using v-bind? I am aware that I can set a value to an attribute dynamically with v-bind, but I would like to add the attribute itself based on a condition. Something ...

Ways to convert an object with values into an array containing those values

To process the JSON data and convert it into an array with the same values for insertion into my PostgreSQL database using pool.query(message, values), where values should be an array if multiple are present. Currently, my object structure is as follows: { ...

Unable to save cookies on mobile browsers, but functioning properly on desktop computers

Currently, I am facing an issue with my ExpressJS app hosted on Heroku and a frontend React app hosted on Netlify. The problem arises when a user logs in successfully and is directed to the home page showing personalized content. Upon landing on the home p ...

Create an HTML table with a line separating two table cells

I need help with creating a table row and td's dynamically using basic HTML and CSS. I would like to draw lines between the td's similar to the example image shown below. Can someone please assist me in achieving this? https://i.sstatic.net/GPd ...

What does the use of square brackets signify in Vuex mutations?

I'm curious about the use of mutation values within brackets in Vuex. What does the code "" represent? export const SOME_MUTATION = 'SOME_MUTATION' Is this just a constant name for a function? If so, why is it enclosed in brackets "[]"? ...

Utilizing a variable beyond the confines of the script tag

Is there a way to assign the value of my variable place to my variable address, even though they are not in the same script tag? I want to bind the value and utilize it for fetching data. When I log my variable place, I can see the address, but I am unsure ...

A captivating opportunity for a web developer specializing in frontend design

Encountered an intriguing dilemma that has me stumped. There is a single stipulation: Only the json can be altered! I am struggling to meet this requirement: data.hasOwnProperty("\u{0030}") class JobHunter { get data() { return &ap ...

merging 4 arrays in a specified order, organized by ID

i have below 4 array objects var dataArray1 = [ {'ProjectID': '001', 'Project': 'Main Project 1', 'StartYear': '2023', 'EndYear': '2023', 'StartMonth': 'Sep&apo ...

Attempting to modify the color of a selected Three.js object causes all objects in the scene to have their colors altered

For example, check out this JSFiddle link. The interesting part occurs during the mousedown event: var hits = raycaster.intersectObjects( [object1, object2, object3] ); if ( hits.length > 0 ) { console.log(hits[ 0 ].object) hits[ 0 ].object.m ...

Display information in a detailed table row using JSON formatting

I have set up a table where clicking on a button toggles the details of the corresponding row. However, I am having trouble formatting and sizing the JSON data within the table. Is there a way to achieve this? This is how I implemented it: HTML < ...

Images are not being shown by Glide JS

I have implemented the Glide JS carousel within a VueJS project to showcase multiple images, however, I am encountering an issue where only the first image is being displayed. The <img/> tag has the correct src URL for all three images, but only th ...

Image Handpicked by JCrop User

Successfully implemented JCrop example code for selecting an area on an image with a preview and getting coordinates. However, the challenge lies in allowing users to select an image from their file system, display it in the browser, and perform the afore ...

Is it necessary for parameter assertion in Javascript to throw an error immediately if the function returns a Promise

I've been immersed in the world of NodeJS code for quite some time now, observing various techniques employed by different developers. One question that has been on my mind is whether it's considered a best practice to have a function that, with ...

Please upload the image by clicking the "Upload Files!" button instead of relying on the input change

I am looking to enhance my image uploading process by allowing users to upload multiple images after clicking the Upload Files! button, rather than relying on the input change event. Below is the jQuery code I am using (which I found here): index.html &l ...

The symbol "#" appears in my URL whenever the link is clicked

Seeking guidance on a URL issue that I am facing. Whenever I click the source link, it adds a pound sign to the URL. How can I prevent this from happening? Can someone assist me in identifying the necessary changes required in my jQuery or HTML code? Bel ...