使用两个 getElementByIds

Using two getElementByIds

是否可以这样做:

this.getElementById('first-id').getElementById('second-id')? 

执行此操作时,出现错误“getElementById(...).getElementById 不是函数。

我尝试这样做的原因是因为我能够控制台记录第一个 id 元素,但不能记录第二个元素(当我这样做时 this.getElementById('second-id'))。我想这是因为我的 DOM 没有完全加载。

但是,我认为既然它加载了第一个 id 元素,我将能够在加载第一部分时执行另一个 getElementById 并且下一个元素是第一个 id 元素的 nested/a 子元素.

谁能解释为什么这个逻辑不起作用?

具有给定 ID 的元素在文档中应该绝对唯一。永远不应有超过一个具有相同 ID 的元素。因此,在 元素 上调用 getElementById 以在其子元素中搜索,如果可能的话(实际上不是),这并没有多大意义 - 相反, 从整个文档中搜索。你应该只需要

document.getElementById('second-id')

您可以使用 Document.querySelector() 链接它,但您永远不需要使用它,因为 ID 应该是唯一的。

例如,像这样:

var selected = document.querySelector('#first-id #second-id');
console.log(selected);
<div id="first-id">
  <div id="second-id">1</div>
</div>
<div id="second-id">2</div>
<!-- Don't use duplicate ids - this is just for demonstration -->

您可以像下面那样做一些奇怪的事情,但这很愚蠢。

<script>
    window.addEventListener("load", function() {
        alert(document.getElementById("parent").ownerDocument.getElementById("child").textContent);
    }, false);
</script>

<div id="parent">
    <div id="child">Yo</div>
</div>

这里的大多数答案都是正确的,将有助于 OP 实施解决方案。这将尝试回答 是否可以做类似的事情:,这是 OP 最初问的:

this.getElementById('first-id').getElementById('second-id')

getElementById() is a Document interface method and is only available on the Documentobject。它在 Element 上不可用,this.getElementById('first-id').getElementById 将等于 undefinedundefined 不是函数,无法调用,因此出现错误。

querySelecetor() 既是一种 document and element 方法,也可用于 object 方法。

这就是为什么你可以做类似的事情:

document.querySelector('#first-id').querySelector('#second-id')

(搜索 #second-id child,共 #first-id