gpt4 book ai didi

javascript - 链接 getElementById

转载 作者:可可西里 更新时间:2023-11-01 02:39:54 26 4
gpt4 key购买 nike

我一直在寻找这个问题的答案,但找不到任何答案,所以我想试试 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;
}

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

关于javascript - 链接 getElementById,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5683087/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com