出于某种原因,…当我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>
发布于 2017-11-27 13:01:55
你想做的是不合逻辑的。
id属性在页面上必须是唯一的。不应该有两个具有相同id的元素
getElementById:通过其ID返回对元素的引用;id是一个字符串,可用于唯一标识元素,即HTML属性中的元素。(https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
Element.id属性表示元素的标识符,反映id全局属性。它在文档中必须是唯一的,并且经常用于使用getElementById检索元素。id的其他常用用法包括在使用CSS对文档进行样式设计时使用元素的ID作为选择器。(https://developer.mozilla.org/en-US/docs/Web/API/Element/id)
这意味着您可以忽略父id,并立即获得子id的元素。
这也是为什么除了getElementById之外,任何东西都不能使用document的原因。没有理由“范围”搜索某种类型的父元素。
https://stackoverflow.com/questions/47511581
复制相似问题