javascript adding new elements with progressive IDs and updating the existing ones

252 views Asked by At

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.

1

There are 1 answers

2
RobG On

The following does what you ask, but I suspect it isn't the result you want.

<script>

// Append a new div after one with id boxn
function add_box(n) {
  var el = document.getElementById('box' + n);
  var div = document.createElement('div');

  div.id = 'box' + ++n;
  div.appendChild(document.createTextNode('New box ' + n));
  el.parentNode.insertBefore(div, el.nextSibling);
  renumberDivs(div, n);
}

// Renumber all sibling divs after el
function renumberDivs(el, n) {

  // Note assignment, not equality
  while (el = el.nextSibling) {
    if (el.tagName && el.tagName.toLowerCase() == 'div'){
      el.id = 'box' + ++n;
    }
  }
}
</script>

<div id="box1">Whatever</div><input type="button" value="add below 1" onclick="add_box(1)">
<div id="box2">Whatever</div><input type="button" value="add below 2" onclick="add_box(2)">
<div id="box3">Whatever</div><input type="button" value="add below 3" onclick="add_box(3)">

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:

<div id="box1">Whatever</div>
<div id="box2">New box 2</div>
<div id="box3">New box 3</div>
<div id="box4">New box 4</div>
<div id="box5">New box 4</div>
<div id="box6">New box 4</div>
<div id="box7">New box 2</div><input type="button" value="add a box" onclick="add_box(1)">
<div id="box8">Whatever</div><input type="button" value="add a box" onclick="add_box(2)">
<div id="box9">Whatever</div><input type="button" value="add a box" onclick="add_box(3)">