Element.prototype in IE7?

前端 未结 3 1346
后悔当初
后悔当初 2020-12-10 07:47

I\'m trying to extend all dom elements so i can get and remove their children. The function is below (works in FF and Chrome). Is there an equivalent in IE7 to extend the ba

相关标签:
3条回答
  • 2020-12-10 08:02

    IE do not have "Element" set, so you can't access the prototype of Element to directly add your function. The workaround is to overload "createElement" and "getElementById" to have them return an element with a modified prototype with your function.

    Thanks to Simon Uyttendaele for the solution!

    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;
            }
    }
    
    0 讨论(0)
  • 2020-12-10 08:21

    Here is a simple workaround that will be sufficient in 99% of cases. It may as well be completed as required by your script :

    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 讨论(0)
  • 2020-12-10 08:23

    No. There will be some limited support in IE8, but 'till then you're better off finding another place to hang your functions.

    0 讨论(0)
提交回复
热议问题