链接getElementById [英] chaining getElementById

查看:108
本文介绍了链接getElementById的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been looking for an answer to this question but I could find none so I thought I'd try StackOverflow.

在javascript中,这是否有效:

In javascript, is this valid:

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

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

I know this can be done with getElementsByTagName but I'm not sure if the object returned by getElementById is able to use the getElementById method.

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

I know that the ID is supposed to be unique per document, but sometimes this is just not the case.

谢谢!

推荐答案

不。

。 ..但是你可以:

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/

这篇关于链接getElementById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆