javascript - IE7 中的 Element.prototype?

标签 javascript dom internet-explorer-7 extend

我正在尝试扩展所有 dom 元素,以便我可以获取和删除它们的子元素。该功能如下(适用于 FF 和 Chrome)。 IE7 中是否有等效项来扩展基本 dom 对象?

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);
}

谢谢!

最佳答案

这是一个简单的解决方法,在 99% 的情况下都足够了。 它也可以按照您的脚本的要求完成:

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;
    }
}

关于javascript - IE7 中的 Element.prototype?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/597268/

相关文章:

javascript - 将 td 元素添加到具有 id 的 tr

python - 使用 Selenium 获取渲染页面的当前 HTML

jquery - Polymer 和 Jquery 选择器

javascript - Internet Explorer 和 removeChild()

javascript - 在使用 modernizr 后也无法在 ie8 和 ie7 上使用我的子菜单?

html - Google 字体(上面有一个空格)无法在 IE7/IE8 上呈现

javascript - 删除Attr()问题

javascript - 无法让 javascript insideHtml 在 WebView 上工作

javascript - 使用任意方法(插件、GreaseMonkey?)在 Chrome 或 Firefox 中使用 JavaScript 移动鼠标光标

javascript - 为什么我的图像没有在 HTML5 Canvas 上绘制?