如何从 getElementById 搜索中获取 ElementById?

How to getElementById from getElementById search?

出于某种原因……当我 getElementById 然后尝试在该元素中搜索另一个 getElementById 它不起作用。
getElementById 中查找 ID 的唯一方法是使用 querySelector 这是为什么?

注意
是的,我知道 querySelector 是一个解决方案......但它没有回答为什么 getElementById > getElementById 不起作用的问题。

getElementById > getElementById 应该可以工作...这是非常简单的代码。我不是要它模拟重力或任何东西。

我有:

document.getElementById("first").getElementById("second").innerHTML = "It works"
<div id="first">
  <div id="second"></div>
</div>

我想要达到的目标:

document.getElementById("first").querySelector("#second").innerHTML = "It works"
<div id="first">
  <div id="second"></div>
</div>

你想做的事不合逻辑。

id 属性在页面上必须 唯一。不应有 2 个具有相同 id:

的元素

getElementById: Returns a reference to the element by its ID; the ID is a string which can be used to uniquely identify the element, found in the HTML id attribute. (source)


The Element.id property represents the element's identifier, reflecting the id global attribute. It must be unique in a document, and is often used to retrieve the element using getElementById. Other common usages of id include using the element's ID as a selector when styling the document with CSS. (source)

这意味着您可以忽略父项 id,并立即获取子项 id 的元素。

这也是为什么 getElementById 除了 document 以外的任何东西都不可用。没有理由 "scope" 搜索某种父元素。

but it doesn't answer the question of why getElementById > getElementById won't work.

因为根据 doc

Unlike some other similar methods, getElementById is only available as a method of the global document object, and not available as a method on all element objects in the DOM. Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function.

并且 document.getElementById("first") 不是 return 文档 ,它 return 是 Element

element

is a reference to an Element object, or null if an element with the specified ID is not in the document.

Element 没有 getElementById 方法。