Posted By

marcio on 01/24/08


Tagged

javascript oop DOM


Versions (?)

Who likes this?

8 people have marked this snippet as a favorite

SpinZ
adix
joomla
rwczippy
vali29
ckayra
seanpowell
aegony


Add and Remove Elements with JavaScript


 / Published in: JavaScript
 

URL: http://www.dustindiaz.com/add-remove-elements-reprise/

Manera increiblemente facil y eficiente de añadir eventos y añadir/borrar nodos

  1. var Dom = {
  2. get: function(el) {
  3. if (typeof el === 'string') {
  4. return document.getElementById(el);
  5. } else {
  6. return el;
  7. }
  8. },
  9. add: function(el, dest) {
  10. var el = this.get(el);
  11. var dest = this.get(dest);
  12. dest.appendChild(el);
  13. },
  14. remove: function(el) {
  15. var el = this.get(el);
  16. el.parentNode.removeChild(el);
  17. }
  18. };
  19.  
  20. var Event = {
  21. add: function() {
  22. if (window.addEventListener) {
  23. return function(el, type, fn) {
  24. Dom.get(el).addEventListener(type, fn, false);
  25. };
  26. } else if (window.attachEvent) {
  27. return function(el, type, fn) {
  28. var f = function() {
  29. fn.call(Dom.get(el), window.event);
  30. };
  31. Dom.get(el).attachEvent('on' + type, f);
  32. };
  33. }
  34. }()
  35. };
  36.  
  37.  
  38.  
  39. //Uso
  40. /*
  41. Event.add(window, 'load', function() {
  42.   var i = 0;
  43.   Event.add('add-element', 'click', function() {
  44.   var el = document.createElement('p');
  45.   el.innerHTML = 'Remove This Element (' + ++i + ')';
  46.   Dom.add(el, 'content');
  47.   Event.add(el, 'click', function(e) {
  48.   Dom.remove(this);
  49.   });
  50.   });
  51. });
  52. */

Report this snippet  

You need to login to post a comment.