简体   繁体   中英

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. By what method or mechanism can I access and modify a DOM element before it is attached to the document?

I have a large DOM element and I want to access a piece of it. I would classically use getElementById , but the DOM element is not attached to the document.

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

I am looking for an answer that does not use jQuery. I love jQuery, but it is not an option for my current problem.

Well, you already have a reference to it with your element variable.

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.

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.

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 .

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.

In your example, you have a reference to the element already. Why do you need to ask the document for it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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