链接getElementById

Sor*_*anu 10 javascript getelementbyid

我一直在寻找这个问题的答案,但我找不到所以我想我会尝试StackOverflow.

在javascript中,这是有效的:

x = document.getElementById('myId'); y = x.getElementById('mySecondId');

我知道这可以完成,getElementsByTagName但我不确定返回的对象getElementById是否能够使用该getElementById方法.

我知道ID应该是每个文档唯一的,但有时情况并非如此.

谢谢!

Zir*_*rak 8

不.

......但你可以:

Element.prototype.getElementById = function(id) {
    return document.getElementById(id);
}
Run Code Online (Sandbox Code Playgroud)

在此页面上尝试:

var x = document.getElementById('footer').getElementById('copyright');
Run Code Online (Sandbox Code Playgroud)

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

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;
}
Run Code Online (Sandbox Code Playgroud)

一个例子:http://jsfiddle.net/3xTcX/

  • 请不要这样做。这是不必要的,因为您可以简单地编写 `document.getElementById()` 而不是扩展 Element 原型,因此它只会使您的代码库复杂化,并使将继承该项目的开发人员感到困惑。零收益。 (5认同)