我一直在寻找这个问题的答案,但我找不到,所以我想我应该试试StackOverflow。
在javascript中,这是否有效:
x = document.getElementById('myId'); y = x.getElementById('mySecondId');
我知道使用getElementsByTagName可以做到这一点,但我不确定getElementById返回的对象是否能够使用getElementById方法。
我知道每个文档的ID应该是唯一的,但有时情况并非如此。
谢谢!
发布于 2011-04-16 07:08:41
不是的。
不过,您可以使用...But:
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/
发布于 2011-04-16 06:53:31
嗯,最好的办法就是试一试。在这种情况下,它将不起作用,因为getElementById方法仅在DOMDocument对象(例如document变量)上可用,而在DOMElement对象上不可用,DOMElement对象是单独的节点。我认为它也应该在那些上可用,但是,嘿,我不同意DOM API的大多数设计……
发布于 2018-10-31 16:17:39
在问题示例中,您可以只使用y = x.querySelector('#'+'mySecondId');而不是y = x.getElementById('mySecondId');。
Element.getElementById不存在,但您可以像其他答案中提到的那样添加它,即使不建议在Element中添加方法。如果你想绝对使用这种解决方案,下面是一种可能性:
Element.prototype.getElementById = function(id) {
return this.querySelector("#"+id);
}在Element.prototype.getElementById中使用element.querySelector而不是document.getElementById的一个优点是,即使元素不在DOM中,element.querySelector也可以工作,比如在使用document.createElement创建元素之后。
https://stackoverflow.com/questions/5683087
复制相似问题