2009-02-28 11 views
6

Estoy tratando de extender todos los elementos dom para que pueda obtener y eliminar a sus hijos. La función está debajo (funciona en FF y Chrome). ¿Hay un equivalente en IE7 para extender el objeto dom base?Element.prototype en IE7?

if (!Element.get) { 
Element.prototype.get = function(id) { 
    for (var i = 0; i < this.childNodes.length; i++) { 
     if (this.childNodes[i].id == id) { 
      return this.childNodes[i]; 
     } 
     if (this.childNodes[i].childNodes.length) { 
      var ret = this.childNodes[i].get(id); 
      if (ret != null) { 
       return ret; 
      } 
     } 
    } 
    return null; 
} 
} 

Element.prototype.removeChildren = function() { 
    removeChildren(this); 
} 

¡Gracias!

+0

víctima http://stackoverflow.com/questions/592815/is-there-really-no-way-to-expose-the-prototype-of-a-html-element-in-ie-8/ – bobince

Respuesta

4

No. Habrá un soporte limitado in IE8, pero 'hasta entonces es mejor que busque otro lugar para colgar sus funciones.

6

Aquí hay una solución simple que será suficiente en el 99% de los casos. Puede también ser completado como es requerido por la secuencia de comandos:

if (!window.Element) 
{ 
    Element = function(){}; 

    var __createElement = document.createElement; 
    document.createElement = function(tagName) 
    { 
     var element = __createElement(tagName); 
     if (element == null) {return null;} 
     for(var key in Element.prototype) 
       element[key] = Element.prototype[key]; 
     return element; 
    } 

    var __getElementById = document.getElementById; 
    document.getElementById = function(id) 
    { 
     var element = __getElementById(id); 
     if (element == null) {return null;} 
     for(var key in Element.prototype) 
       element[key] = Element.prototype[key]; 
     return element; 
    } 
} 
+0

eliminé mi respuesta y edité esta, no tuve suficiente reputación para hacerlo antes –

3

IE no tienen conjunto "elemento", por lo que no se puede acceder al prototipo de elemento para agregar directamente a su función. La solución es sobrecargar "createElement" y "getElementById" para que devuelvan un elemento con un prototipo modificado con su función.

¡Gracias a Simon Uyttendaele por la solución!

if (!window.Element) 
{ 
     Element = function(){} 

     Element.prototype.yourFunction = function() { 
       alert("yourFunction"); 
     } 


     var __createElement = document.createElement; 
     document.createElement = function(tagName) 
     { 
       var element = __createElement(tagName); 
       for(var key in Element.prototype) 
         element[key] = Element.prototype[key]; 
       return element; 
     } 

     var __getElementById = document.getElementById 
     document.getElementById = function(id) 
     { 
       var element = __getElementById(id); 
       for(var key in Element.prototype) 
         element[key] = Element.prototype[key]; 
       return element; 
     } 
}