Skip to content
Advertisement

Button changing newest div item instead of the correct

I created a div table of sorts, where there is a button, and that button creates a box, and what is supposed to happen is that you can click any of the {x} boxes and it colors it black However, instead of coloring that box black(or white), it colors the newest one black(or white). How do I change this?

HTML:

JavaScript

Javascript:

JavaScript

CSS:

JavaScript

Advertisement

Answer

I think the problem is in the test function.

JavaScript

You’re setting the id to "combined" for every new added element. But an id must be unique for each element in the whole html document. May be you intended to do the following.

JavaScript

Your code is very cluttered with poor naming and lots of unused variables and functions, so I’ve tried to refactor a little!

JavaScript
JavaScript
JavaScript

Here I’ve used event delegation to listen on click event on any grid items. So if we listen for click events on the #content element and use the event.target then we get the grid item that has been clicked on. Then we can pass that element to the changeColor method.

If you don’t understand anything feel free to ask me in the comment. Hope this helps.

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