i am making a chess game using js html and css what i am trying to do is i have given every pawn an onclick function which gets id of pawns parent div/block and based on that it highlights the blocks where the pawn can go but when i get the id of parent div it gives me id of another div idk why can some one help me
my code
html
<div id="7b" ><button ></button></div>
<div id="7b"><button ></button><div id="mp1" ></div></div>
<div id="7b" ><button ></button></div>
<div id="7b"><button ></button><div id="mp2" ></div></div>
<div id="7b" ><button ></button></div>
<div id="7b"><button ></button><div id="mp3" ></div></div>
<div id="7b" ><button ></button></div>
<div id="7b"><button ></button><div id="mp4" ></div></div>
<div id="8b"><button ></button><div id="mp5" ></div></div>
<div id="8b" ><button ></button></div>
<div id="8b"><button ></button><div id="mp6" ></div></div>
<div id="8b" ><button ></button></div>
<div id="8b"><button ></button><div id="mp7" ></div></div>
<div id="8b" ><button ></button></div>
<div id="8b"><button ></button><div id="mp8" ></div></div>
<div id="8b" ><button ></button></div>
js
for (let i=0; i<8; i ) {
let blps = document.getElementsByClassName("blp")[i]
let whps = document.getElementsByClassName("whp")[i]
whps.onclick = function() {moveblp(i)};
blps.onclick = function() {movewhp(i)};
}
function movewhp(a) {
let pawn = document.getElementsByClassName("whp")[a]
let parent = Number.parseInt(pawn.parentElement.id)
console.log(parent)
}
b stands for block and r stands for row i have 8x8 rows so total 64 parent divs
CodePudding user response:
The reason is because you have multiple similar ids used. (multiple 7b
s and 8b
s id). To fix this, change those ids to unique ids.
CodePudding user response:
The ID attribute must be unique:
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
Try using, with the same mechanics, a class instead of an id, by invoking "getElementsByClassName" you will get a collection of elements that correspond to the elements you want to highlight. Using IDs you would only get the first element of the list..
EDIT:
Try modifying your for loop as follows:
const blps = document.getElementsByClassName("blp");
const whps = document.getElementsByClassName("whp");
for (let i = 0; i < 8; i ) {
const whpsItem = whps.item(i);
const blpsItem = blps.item(i)
whpsItem.onclick = function () {
moveblp(whpsItem);
};
blpsItem.onclick = function () {
movewhp(blpsItem);
};
}
In any case I wouldn't use the index to refer to the DIV, you could pass the clicked element directly to the movewhp
function
function movewhp(pawn) {
let parent = Number.parseInt(pawn.parentElement.id)
console.log(parent)
}