Skip to content
Advertisement

What am I doing wrong in scoping my function?

In this test case, I am using append.child with plain JavaScript to add 3 kinds of divs (blue, red, green) to a parent multiple times according to their corresponding button onclicks, then I am adding another child inside the added div with another button (innerButton).

My issue is that, the onclick function which is assigned to the innerbutton and is nested within the initial function, listens only to the very first appended div, and it adds the input (which is supposed to be added to the div I’m clicking on) to the last append element of its ‘kind’. I am doing something wrong with my scoping but I can’t see it. I just started studying JavaScript, so I am not familiar yet with libraries, jQuery etc.

JavaScript
JavaScript
JavaScript

Advertisement

Answer

The first thing you need to know is that, although you can technically add the same id to multiple elements, it is bad practice to do so. The id of an element should be unique. If you need to apply the same style or target multiple elements with your code you should use class instead of id. I think that’s what is causing issues in your code.

Second, since you say you are learning, i think it would be good if you tried to make a single function to add the elements since the code is repeated in all of the three functions, except for the color. Try making the function accept the color as a variable so you can reuse it for the three colors. Imagine if it was a hundred colors.

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