2011-04-15 83 views
9

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

在JavaScript中,这是有效的:

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

我知道这可以用getElementsByTagName做,但我不知道如果getElementById返回的对象是能够使用getElementById方法。

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

谢谢!

+0

考虑[jQuery](http://jquery.com/)。 – 2011-04-15 22:53:04

+0

或[MooTools](http://mootools.net/)(它扩展了'DOMElement'对象以支持'getElementById'方法)。 – 2011-04-15 22:54:08

回答

5

没有。

...但是你可以,但:

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/

+1

事情是,你可以多次分配相同的ID。虽然这会产生无效的HTML,但每个浏览器都可以处理它。但是,'document.getElementById()'将始终返回第一个匹配项。 – user123444555621 2011-04-16 08:01:27

+0

@ Pumbaa80 - 我看到...有趣。更新我的答案。 – Zirak 2011-04-16 11:32:34

+0

哇,谢谢你的详尽答案和例子。它*完全*我需要的! :) – 2011-04-17 17:16:57

0

没有。

默认情况下,只有document对象具有方法getElementById

即使x是一个iframe或其他东西,你仍然必须访问其他属性或任何东西,然后再到另一个getElementById

2

那么,找出最好的方法就是尝试一下。在这种情况下,它将不起作用,因为getElementById方法仅适用于DOMDocument对象(例如document变量)而不是DOMElement对象(它们是单独的节点)。我认为它应该已经可以用于这些,但是,嘿,我不同意大多数DOM API的设计......

+0

嗯,我正在尝试它,但没有成功:)。我去Firebug在控制台中尝试它,当我键入'x.'时,我注意到'getElementById'不在方法列表中。这就是我的想法。谢谢! :) – 2011-04-15 22:58:21

+0

@Sorin:没问题。 :) – 2011-04-15 23:02:52

0

考虑当有超过一个

也许一类或自定义属性,最好不要使用ID,就可以使用document.querySelectorAll翅片他们。

els = document.querySelectorAll('[custom-attr]') 
0

这是一个基于Node.contains

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

最后一行快速替代(在最新的Chrome和Firefox异形)的性能比jQuery的等价

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

唯一的快4倍至10倍不错的选择是querySelector(有点快)

container.querySelector('#my-element-id');