且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

链接getElementById

更新时间:2023-11-27 13:42:28

不。

。 ..但是你可以:

Element.prototype.getElementById = function(id) {
    return document.getElementById(id);
}

在此页面上尝试:

var x = document.getElementById('footer').getElementById('copyright');

编辑:正如Pumbaa80指出的那样,你想要别的东西。好吧,就是这样。请谨慎使用。

As Pumbaa80 pointed out, you wanted something else. Well, here it is. Use with caution.

Element.prototype.getElementById = function(req) {
    var elem = this, children = elem.childNodes, i, len, id;

    for (i = 0, len = children.length; i < len; i++) {
        elem = children[i];

        //we only want real elements
        if (elem.nodeType !== 1 )
            continue;

        id = elem.id || elem.getAttribute('id');

        if (id === req) {
            return elem;
        }
        //recursion ftw
        //find the correct element (or nothing) within the child node
        id = elem.getElementById(req);

        if (id)
            return id;
    }
    //no match found, return null
    return null;
}

示例: http://jsfiddle.net/3xTcX/