I am trying to create a loop that will post to the DOM three times in three different areas. Basically I have an array of enemies that I want to get 3 random ones then post this information to an three HTML div classes (firstEnemy, secondEnemy, thirdEnemy). I am aware that I can just :
let loadEnemies = document.querySelector(".firstEnemy");
loadEnemies.innerHTML =
'<p>Name: ' randomLowEnemy.name '</p>'
'<p>Health: ' randomLowEnemy.health '</p>'
but to do this three times(plus more for different ranks) will be difficult; thus I was trying to create a loop that can automatically do it for me. So far I can get an enemy and post it:
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;
};
//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];
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>'
}
CodePudding user response:
The selection of the random enemy has to be in the loop, and you need to loop over the elements to assign them to.
Give all the enemy DOM elements the same class enemy
, rather than '.firstEnemy', '.secondEnemy', '.thirdEnemy'
, so you can easily loop over them together.
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>';
});