我一直在寻找这个问题的答案,但我找不到所以我想我会尝试StackOverflow。
在javascript中,这是有效的:
x = document.getElementById('myId');
y = x.getElementById('mySecondId');
我知道这可以用getElementsByTagName
完成,但我不确定getElementById
返回的对象是否能够使用getElementById
方法。
我知道ID应该是每个文档唯一的,但有时情况并非如此。
谢谢!
不。
......但你可以:
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;
}
那么,最好的方法就是尝试一下。在这种情况下,它不起作用,因为getElementById
方法仅在DOMDocument
对象(例如document
变量)上可用,而不在DOMElement
对象上可用,y = x.querySelector('#'+'mySecondId');
对象是单个节点。我认为它应该也可用于那些,但是,嘿,我不同意DOM API的大部分设计......
你可以在问题的样本中使用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
创建它之后。
不。
只有getElementById
对象默认使用x
方法。
即使getElementById
是一个iframe或者其他什么东西,在你到达另一个document.querySelectorAll
之前,你仍然需要访问其他一些属性或其他什么。
当有多个时,请考虑不使用id
也许一个类或自定义属性更好,然后你可以使用els = document.querySelectorAll('[custom-attr]')
来鳍它们。
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);
的快速替代方案
$('#my-element-id', container);
最后一行(在最新的Chrome和Firefox上进行了分析)比jQuery等效的速度快4到10倍
querySelector
唯一的好选择是container.querySelector('#my-element-id');
(更快一点)
qazxswpoi