链接getElementById

问题描述 投票:9回答:6

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

在javascript中,这是有效的:

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

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

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

谢谢!

javascript getelementbyid
6个回答
8
投票

不。

......但你可以:

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

在此页面上尝试:

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

编辑:正如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;
}

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


2
投票

那么,最好的方法就是尝试一下。在这种情况下,它不起作用,因为getElementById方法仅在DOMDocument对象(例如document变量)上可用,而不在DOMElement对象上可用,y = x.querySelector('#'+'mySecondId');对象是单个节点。我认为它应该也可用于那些,但是,嘿,我不同意DOM API的大部分设计......


1
投票

你可以在问题的样本中使用y = x.getElementById('mySecondId');而不是Element.getElementById

Element不存在,但您可以像其他答案中提到的那样添加它,即使不建议将方法添加到Element.prototype.getElementById = function(id) { return this.querySelector("#"+id); } 。如果你想绝对使用这种解决方案,下面是一种可能性:

element.querySelector

document.getElementById中使用Element.prototype.getElementById而不是element.querySelector的一个好处是,即使元素不在DOM中,document.createElement也在工作,例如在用document创建它之后。


0
投票

不。

只有getElementById对象默认使用x方法。

即使getElementById是一个iframe或者其他什么东西,在你到达另一个document.querySelectorAll之前,你仍然需要访问其他一些属性或其他什么。


0
投票

当有多个时,请考虑不使用id

也许一个类或自定义属性更好,然后你可以使用els = document.querySelectorAll('[custom-attr]') 来鳍它们。

Node.contains

0
投票

这是基于var getById = function(id, context) { var el = document.getElementById(id); return context.contains(el) ? el : null; } var container = document.getElementById('container-element'); getById('my-element-id', container); 的快速替代方案

$('#my-element-id', container);

最后一行(在最新的Chrome和Firefox上进行了分析)比jQuery等效的速度快4到10倍

querySelector

唯一的好选择是container.querySelector('#my-element-id'); (更快一点)

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.