How to use javascript to add an image to a div on click [closed]

1 week ago 12
ARTICLE AD BOX

You have said that you want to add your bishop image to the 'instance of the chess-square class that is clicked', but you then are using getElementById in your code. Unfortunately getElementById is for unique elements specified by their ID property.

Instead you need to use a method such as querySelectorAll and then iterate over the resulting NodeList.

Something like

const newImage = document.createElement("img"); newImage.src = "your_bishop_image.png"; document.querySelectorAll(".chess-square").forEach(function(element) { element.addEventListener("click", function(target){ target.appendChild(newImage); }); })

This is just one way of doing it as an example. There may be better ways of doing what you're setting out to do that involve setting up reactivity or standard event handlers, but that's outside of the scope of your question. I'd generally advise getting a solid grounding in JS fundamentals to tackle an app like this.

See also: https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll

ChrisM's user avatar

1 Comment

This may work (although again it makes assumptions about the OP's HTML structure which they haven't provided - instead they are spending their time posting grumbling comments rather than responding to feedback) but it gives no control over the actual flow of the game. So, someone could click on every square and add 64 bishops to the board. So again, the OP needs to rethink the overall approach to their game engine quite substantially.

2025-11-24T13:14:17.967Z+00:00

Read Entire Article