Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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.?

share|improve this question
3  
MY advice is to use Jquery for this. It simplifies it a lot. You can find a lot of info here: api.jquery.com/append –  Hristo Valkanov May 21 at 0:20
2  
1  
Learn about DOM manipulation: quirksmode.org/dom/intro.html . –  Felix Kling May 21 at 0:22
3  
@IvayloToskov w3schools is a bad site and is looked down on by SO –  Stephen P May 21 at 0:22
1  
@user3550435 - What have you tried? Have you made any attempts to do this or do you just want teh codez? –  Stephen P May 21 at 0:26
show 1 more comment

2 Answers

up vote 0 down vote accepted
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.

share|improve this answer
add comment

To remove you could use

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

To add you could use

$("<div id='new'></div>").appendTo('#id');
share|improve this answer
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 at 0:26
    
Yes that is indeed a good point I will fix my answer. –  JordanD May 21 at 0:27
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.