-2

If I have a bunch of HTML code, similar to the following:

<div id='test0div'>
   <p id='test0'></p>
</div>

How do I use JavaScript to add or remove more of those - i.e.

<div id='test1div'>
   <p id='test1'></p>
</div>
<div id='test2div'>
   <p id='test2'></p>
</div>

...etc.?

  • 3
    MY advice is to use Jquery for this. It simplifies it a lot. You can find a lot of info here: http://api.jquery.com/append/ – Hristo Valkanov May 21 '14 at 00:20
  • 2
    http://www.w3schools.com/js/js_htmldom_html.asp http://stackoverflow.com/questions/584751/inserting-html-into-a-div http://www.w3schools.com/js/js_htmldom_css.asp http://stackoverflow.com/questions/566203/changing-css-values-with-javascript – Ivaylo Toskov May 21 '14 at 00:21
  • 1
    Learn about DOM manipulation: http://quirksmode.org/dom/intro.html . – Felix Kling May 21 '14 at 00:22
  • 3
    @IvayloToskov w3schools is a bad site and is [looked down on](http://w3fools.com) by SO – Stephen P May 21 '14 at 00:22
  • Sort of anticipating some other answers (I saw some stuff on the web, such as addelement/removeelement), how do you control where the elements are inserted? – user3550435 May 21 '14 at 00:25
  • 1
    @user3550435 - What have you tried? Have you made any attempts to do this or do you just [want teh codez](http://programmers.stackexchange.com/q/129950)? – Stephen P May 21 '14 at 00:26

2 Answers2

0

To remove you could use

$('#id').remove();

To add you could use

$("<div id='new'></div>").appendTo('#id');
Jordan.J.D
  • 7,999
  • 11
  • 48
  • 78
  • 1
    Note that this is not "pure" javascript and requires the jQuery Library. @JordanD you shouldn't assume every one is using jquery, and the question is not tagged with jquery. – Jon P May 21 '14 at 00:26
0
var container = document.createElement("div");
for(var i=0; i<5; i++) { // change i <5 as per your data source
   var div = document.createElement("div");
   var p = document.createElement("p");
   p.id = "test"+i;
   div.id = "test"+i+"div";
   div.appendChild(p);
   container.appendChild(div); // you can event append to particular id or body    
}

   // document.getElementById("divId").appendChild(container);

container, will have all the divs & p as you wish This will give you the output you want. Just change the number of times the loop will execute based on your wish.

mohamedrias
  • 18,326
  • 2
  • 38
  • 47