I iterate over the array and modify the contents of the array, but I do not get the expected results. What am I missing or is something wrong?
I have two div groups (one with an attacking class and another adversary) with three elements each. I am trying to select one element on each side, creating a border around it. Now I want to switch classes from attacking to enemy and vice versa. But when I use for loop, it somehow ignores some elements and changes only one or two div classes. Here is my code:
HTML:
<div id="army1">
<div class="attacker">
<img src="img/Man/Archer.jpg" />
<div class="hp"></div>
</div>
<br><div class="attacker">
<img src="img/Man/Knight.jpg" />
<div class="hp"></div>
</div>
<br><div class="attacker">
<img src="img/Man/Soldier.jpg" />
<div class="hp"></div>
</div>
<br>
</div>
<div id="army2">
<div class="enemy">
<img src="img/Orcs/Crossbowman.jpg" />
<div class="hp"></div>
</div>
<br><div class="enemy">
<img src="img/Orcs/Mine.jpg" />
<div class="hp"></div>
</div>
<br><div class="enemy">
<img src="img/Orcs/Pikeman.jpg" />
<div class="hp"></div>
</div>
<br>
</div>
And my javascript code:
var attacker = document.getElementsByClassName('attacker');
var enemy = document.getElementsByClassName('enemy');
var button = document.getElementById("fight");
for (var i = 0; i < attacker.length; i++) {
attacker[i].onclick = function () {
if (this.getAttribute('class') != 'attacker first') {
resetAttackerClasses();
this.setAttribute('class', 'attacker first');
} else {
resetAttackerClasses();
}
};
}
for (var i = 0; i < enemy.length; i++) {
enemy[i].onclick = function () {
if (this.getAttribute('class') != 'enemy second') {
resetEnemyClasses();
this.setAttribute('class', 'enemy second');
} else {
resetEnemyClasses();
}
};
}
button.onclick = function() {
document.getElementsByClassName('enemy second')[0].children[1].style.width = '50px';
resetAttackerClasses();
resetEnemyClasses();
for (var i = 0; i < attacker.length; i++) {
attacker[i].setAttribute('class', 'enemy');
enemy[i].setAttribute('class', 'attacker');
};
};
function resetAttackerClasses() {
for (var i = 0; i < attacker.length; i++) {
attacker[i].setAttribute('class', 'attacker');
};
}
function resetEnemyClasses() {
for (var i = 0; i < attacker.length; i++) {
enemy[i].setAttribute('class', 'enemy');
};
}
source
share