getElementById在运行时动态创建元素的位置 [英] getElementById Where Element is dynamically created at runtime
问题描述
我在运行时使用innerHTML标签创建了一个对象,现在我想通过使用getElementById来访问这个元素,当我访问该元素时它返回NULL值。请建议我任何指示,以便我能够实现这一点,
I have created an object at runtime by using innerHTML tag, now I want to access this element by using getElementById, when I accessed the element its return NULL value. Kindly suggest me any direction so that I can acheive this,
以下是我正在使用的以下代码提示
Here is the following code hint which I am using
在HTML中
<div id="web">
<object id="test"></object>
</div>
在JS中
document.getElementById("web").innerHTML="<object id='test2'></object>";
.
.
var obj = document.getElementById("test2");
这里obj返回空值。
推荐答案
您是否为新创建的元素分配了ID?您是否将元素插入文档树(使用 appendChild
或 insertBefore
)?只要该元素未插入DOM,就无法使用 document.getElementById
检索它。
Did you assign an id to the freshly created element? Did you insert the element into the document tree (using appendChild
or insertBefore
)? As long as the element is not inserted into the DOM, you can't retrieve it using document.getElementById
.
元素创建示例:
var myDiv = document.createElement('div');
myDiv.id = 'myDiv';
document.body.appendChild(myDiv);
document.getElementById('myDiv').innerHTML = 'this should have worked...';
[编辑]鉴于后来提供的代码,第三个问题出现了:您的脚本位于html页面的底部(在结束< / body>
标记之前)?如果它位于文档的标题中,则在文档树完全呈现之前,您的脚本可能正在运行。如果您的脚本必须位于文档的标题中,则可以使用加载处理程序在呈现文档后运行它:
[edit] Given the later supplied code, a third question emerges: is your script located at the bottom of your html page (right before the closing </body>
tag)? If it's in the header of the document, your scripting may be running before the document tree is completely rendered. If your script has to be in the header of the document, you could use a load handler to run it after rendering of the document:
window.onload = function(){
document.getElementById("web").innerHTML='<object id="test2"></object>';
// [...]
var obj = document.getElementById('test2');
};
这篇关于getElementById在运行时动态创建元素的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!