Skip to content
Advertisement

Cannot access element after creating it with append child

I am trying to create a chess game using html and js.

Here is part of my HTML code:

JavaScript

Here is the JS

JavaScript

Everything works fine but the problem is when I use append child to copy image , I can no longer select the copied image. I can still select original one.

Advertisement

Answer

The problem is that you are appending a new image that does not have onclick event listener, id or a className. So you would have to add those to the new appended image.

But even if you do that there is another problem which is that the image onclick and the onclick of the square that the new image is on will both fire at the same time making the image just move in its place.

To solve both of these problems in a simple way I suggest that you just add the move handler to all the squares and then inside check if the current square has any child nodes. If it does then just return.

JavaScript

And ofcourse you would want later to add more logic if the square is occupied by enemy.

Now for moving the image from one square to another you can simply append the current selected image to the new square and it will be remove from the old one so no need to create new images:

JavaScript

Here is a simple runnable example of the suggested fixes. The css and the opacity stuff are just for demo:

JavaScript
JavaScript
JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement