Add/Remove HTML element


/ Published in: JavaScript
Save to your folder(s)



Copy this code and paste it in your HTML
  1. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
  5. <title>Add/Remove child: Javascript</title>
  6. <script>
  7. function addEvent() {
  8. var ni = document.getElementById('myDiv');
  9. var numi = document.getElementById('theValue');
  10. var num = (document.getElementById("theValue").value -1)+ 2;
  11. numi.value = num;
  12. var divIdName = "my"+num+"Div";
  13. var newdiv = document.createElement('div');
  14. newdiv.setAttribute("id",divIdName);
  15. newdiv.innerHTML = "Element Number " + num + " has been added! <a href=\"javascript:;\" onclick=\"removeElement(\'"+divIdName+"\')\">Remove the element &quot;"+divIdName+"&quot;</a>";
  16. ni.appendChild(newdiv);
  17. }
  18.  
  19. function removeElement(divNum) {
  20. var d = document.getElementById('myDiv');
  21. var olddiv = document.getElementById(divNum);
  22. d.removeChild(olddiv);
  23. }
  24. </script>
  25. <style type="text/css" media="screen">
  26. .updated {
  27. background: #FFE2AF;
  28. color: #000;
  29. border: 2px solid #ccc;
  30. padding: 1em;
  31. }
  32. </style>
  33. </head>
  34.  
  35. <body>
  36. <div class="updated">
  37. <strong>UPDATE</strong>: There is a newer "up-to-date" version of this tutorial that can be found here:
  38. <a href="http://www.dustindiaz.com/add-remove-elements-reprise/">Add and Remove Elements with JavaScript (reprise)</a>.
  39. </div>
  40.  
  41. <input type="hidden" value="0" id="theValue" />
  42. <p><a href="javascript:;" onclick="addEvent();">Add Some Elements</a></p>
  43. <div id="myDiv"> </div>
  44. </body>
  45. </html>

URL: http://www.dustindiaz.com/add-and-remove-html-elements-dynamically-with-javascript/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.