I have already 3 existing boxes on a page (divs) with a unique ID (1,2,3) each. I want to have a button by each one of them that allows the user to add new boxes right below. These boxes should follow the already existing numbering. However, doing this will also imply to update the IDs of the already existing boxes underneath the new ones so the numbers match.
This is my code:
function add_box(n) {
document.getElementById("box"+(n<)).setAttribute("id", "box");
var div = document.createElement("div");
div.id="box"+(n+1);
var txt = document.createTextNode("A new box");
div.appendChild(txt);
var newbox = document.getElementById("box"+n);
insertAfter(div,newbox);
}
HTML
<div id="box1">Whatever</div><input type="button" onclick="add_box(1)">
<div id="box2">Whatever</div><input type="button" onclick="add_box(2)">
<div id="box3">Whatever</div><input type="button" onclick="add_box(3)">
Its obviously not working because i guess i need to have an array with all the elements that contain "box" in the ID and then somehow update their numbers but i dont know how to do all that.
Thank you.
The following does what you ask, but I suspect it isn't the result you want.
Note that in the above, numbers are passed as arguments that are treated as numbers but also implicitly converted to strings when used for the ID value. That sort of type conversion isn't really liked, consider using a more explicit method.
After a few clicks, you may end up with something like: