Incrementing getelementbyid

Joined
Jan 6, 2022
Messages
2
Reaction score
0
I have a javascript that creates multiple elements when you click a button. The first element that is created is a DIV tag and the id of the DIV tag is auto-incremented by 1 every time the button is clicked. Div tag attribute is this: w.id = 'myDiv + i++; which does work. Everyt time a button is pressed a new DIV tag is created and increments the id with +1. Div1, Div2, Div3 etc.

The issue is that I am trying to append child elements to the div tag that was created. So for each DIV tag there are 3 new elements which are appended to the DIV tag. document.getElementById("myDiv").appendChild(y);

I have read about Closures, creating global variables as well but can not seem to figure out how to get the correct id for each subsequent DIV tag that is created so that I can append the child elements.

I have tried
document.getElementById("myDiv" + i++).appendChild(y);
document.getElementById("myDiv" + i).appendChild(y);
document.getElementById("myDiv").appendChild(y); as well as counteless other attempts.

Also attempted a closure but it kept printing out the function instead of the integer. Attempted to add () to the onclick function for the button to call the closure and that didn't work either.

I can append child elements to the first DIV tag only, when you click the button again, the child elements are appended to the first div which the id is Div1, but when Div2 is created the child elements are still being appended to Div1 instead of Div2.

So each time you add a new Div the Div id should increment by 1 and have 3 child elements appended to it.

Literally, I have read countless articles and have tried through trial and error to figure this out and can't seem to. I am very new to Javascript and would like to do this correctly without taking any shortcuts.
 
Joined
Nov 13, 2020
Messages
302
Reaction score
38
Let me start by saying "You're lucky I looked here since JavaScript is a different language than Java and JS has its own section."
The appendChild method does not give an ID nor a class to the appended. You need to do that separately using the
document.getElementsByTagName("div")[1].setAttribute("id", 101); method.

Good luck
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,149
Members
46,695
Latest member
StanleyDri

Latest Threads

Top