I am making a chess game, I wanna move the pieces using the drag and drop.
document.addEventListener("drop", function(event) {
if (event.target.className == "square") {
//remove the piece from the original square
dragged.parentElement.removeChild(dragged);
//add the piece to the new square
event.target.appendChild(dragged);
}
if (event.target.className == "piece") {
//remove the piece from the original square
dragged.parentElement.removeChild(dragged);
//remove the piece of the new square
event.target.parentElement.removeChild(event.target);
//add the piece to the new square
event.target.parentElement.appendChild(dragged);
}
})
If the square where the piece will move is empty, the event target is the square element.
If the square is occupied by another piece, the event target is that piece.
The first if statement is working fine, but there is a problem in the second if, when I add the piece to new square, the event.target.parentElement
becomes null, which throw this error:
Cannot read properties of null (reading 'appendChild').
Can you help me fix this issue. Thank you
CodePudding user response:
After you do event.target.parentElement.removeChild(event.target);
, the target element is no longer a child, so it doesn't have a parent.
Save the parent element in a variable so you can refer to it again.
document.addEventListener("drop", function(event) {
if (event.target.className == "square") {
//remove the piece from the original square
dragged.parentElement.removeChild(dragged);
//add the piece to the new square
event.target.appendChild(dragged);
}
if (event.target.className == "piece") {
//remove the piece from the original square
dragged.parentElement.removeChild(dragged);
let parent = event.target.parentElement;
//remove the piece of the new square
parent.removeChild(event.target);
//add the piece to the new square
parent.appendChild(dragged);
}
})
CodePudding user response:
event.target.parentElement.removeChild(event.target);
Completely Removes The Existence Of "event.target
"....
solution
if you are use some data stored in text form to represent every piece
then you can set that data to " " , instead of remove child
OR
You Just Overwrite On The new sqaure
..If the Problem Is not Solved Post More Of Your Code Where It will be easier to Understand