简体   繁体   English

JS getElementById创建的元素

[英]JS getElementById on created element

I'm not sure if this is possible, but I am creating an element using document.createElement, then appending child elements to that variable to build a sort of template prior to adding it to the page. 我不确定是否可行,但是我正在使用document.createElement创建一个元素,然后将子元素附加到该变量以构建某种模板,然后再将其添加到页面。 As such, this element is not in DOM yet. 因此,此元素不在DOM中。 I'd like to be able to directly access the child elements by their ID, rather than trying to use the children property to find them. 我希望能够通过其ID直接访问子元素,而不是尝试使用children属性来查找它们。 Is it possible to use something like element.getElementById to find child elements within that parent element before it's added to DOM, as if it were its own mini-DOM? 是否可以使用诸如element.getElementById之类的东西在将其添加到DOM之前在该父元素中查找子元素,就好像它是自己的迷你DOM一样?

rough example: 粗略的例子:

var parentElmt = document.createElement('DIV');
var childElmt = document.createElement('DIV');
childElmt.id = "child1";
parentElmt.appendChild(childElmt);
parentElmt.getElementById('child1').innerHTML = "Does this work?";

If you already have a reference to the child element, you should just use that: 如果已经有了对child元素的引用,则应使用该元素:

 var root = document.getElementById("root") var parentElmt = document.createElement('div'); var childElmt = document.createElement('div'); childElmt.id = "child1"; parentElmt.appendChild(childElmt); // you already have the ref to childElmt. childElmt.innerHTML = "Does this work?"; root.appendChild(parentElmt) 
 <div id="root"></div> 

Alternatively you could reselect the child. 或者,您可以重新选择孩子。

 var root = document.getElementById("root") var parentElmt = document.createElement('div'); var childElmt = document.createElement('div'); childElmt.id = "child1"; parentElmt.appendChild(childElmt); // you can use querySelector let ch = parentElmt.querySelector("#child1") ch.innerHTML = "Does this work?"; root.appendChild(parentElmt) 
 <div id="root"></div> 

If your goal is just to select the child element, you can use querySelector , like so: 如果您的目标只是选择子元素,则可以使用querySelector ,如下所示:

parentElmt.querySelector('#child1')

You can use getElementById only on the document . 您只能在document上使用getElementById

Unlike some other element-lookup methods such as Document.querySelector() and Document.querySelectorAll(), 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. 与其他一些元素查找方法(例如Document.querySelector()和Document.querySelectorAll())不同,getElementById()仅可用作全局文档对象的方法,而不适用于DOM中所有元素对象的方法。 Because ID values must be unique throughout the entire document, there is no need for "local" versions of the function. 因为ID值在整个文档中必须唯一,所以不需要该功能的“本地”版本。

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById#Notes https://developer.mozilla.org/zh-CN/docs/Web/API/Document/getElementById#Notes

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM