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


i have 3 existing boxes on page (divs) unique id (1,2,3) each. want have button each 1 of them allows user add new boxes right below. these boxes should follow existing numbering. however, doing imply update ids of existing boxes underneath new ones numbers match.

this 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 not working because guess need have array elements contain "box" in id , somehow update numbers dont know how that.

thank you.

the following ask, suspect isn't result want.

<script>  // append new div after 1 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 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 in above, numbers passed arguments treated numbers implicitly converted strings when used id value. sort of type conversion isn't liked, consider using more explicit method.

after few clicks, may end 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 box" onclick="add_box(1)"> <div id="box8">whatever</div><input type="button" value="add box" onclick="add_box(2)"> <div id="box9">whatever</div><input type="button" value="add box" onclick="add_box(3)"> 

Comments

Popular posts from this blog

c++ - OpenMP unpredictable overhead -

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

javascript - Wordpress slider, not displayed 100% width -