[英]Use getElementById on newly created DOM object before it is inserted into the document — HOW?
The getElementById
method cannot be used unless the DOM element is attached to the document. 除非将DOM元素附加到文档,否则无法使用
getElementById
方法。 By what method or mechanism can I access and modify a DOM element before it is attached to the document? 在将DOM元素附加到文档之前,我可以通过什么方法或机制来访问和修改它?
I have a large DOM element and I want to access a piece of it. 我有一个大的DOM元素,我想访问它的一部分。 I would classically use
getElementById
, but the DOM element is not attached to the document. 我经常使用
getElementById
,但DOM元素没有附加到文档。
var element = document.createElement("div");
element.id = 'testqq';
var el = document.getElementById('testqq'); // el will be null!
source: https://developer.mozilla.org/en/dom/document.getelementbyid 来源: https : //developer.mozilla.org/en/dom/document.getelementbyid
I am looking for an answer that does not use jQuery. 我正在寻找一个不使用jQuery的答案。 I love jQuery, but it is not an option for my current problem.
我喜欢jQuery,但它不是我当前问题的选择。
Well, you already have a reference to it with your element
variable. 好吧,你已经有了
element
变量的引用。
But I'll bet you mean you want something nested inside. 但我敢打赌你的意思是你想要嵌套内部的东西。 If that's right, you could use
getElementsByTagName('*')
, then iterate over the collection that's returned, testing the ID property until yours is found. 如果这是正确的,您可以使用
getElementsByTagName('*')
,然后迭代返回的集合,测试ID属性,直到找到您的。
var div = document.createElement('div');
div.innerHTML = '<p>yo</p><div><span id="tester">hi</span></div>';
var all = div.getElementsByTagName('*');
// search for element where ID is "tester"
for (var i = 0, len = all.length; i < len; i++) {
if (all[i].id === 'tester') {
var result = all[i];
break;
}
}
alert( result.id );
Before you try the loop, you can test to see if querySelectorAll
is supported in the browser, and use that if so. 在尝试循环之前,您可以测试浏览器是否支持
querySelectorAll
,如果是,则使用它。
if( div.querySelectorAll ) {
var result = div.querySelectorAll('#tester');
} else {
// Do the loop with getElementsByTagName()
}
The document.createElement
function returns a new element object, but that element doesn't exist in the DOM until you insert it . document.createElement
函数返回一个新的元素对象,但在插入之前 ,该元素在DOM中不存在。
The document object has no recollection of elements you asked it to create, so when you call document.getElementById('testqq')
, it has absolutely no idea what you're looking for. 文档对象没有您要求它创建的元素的回忆,因此当您调用
document.getElementById('testqq')
,它完全不知道您在寻找什么。
In your example, you have a reference to the element already. 在您的示例中,您已经引用了该元素。 Why do you need to ask the document for it?
你为什么要问这份文件呢?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.