简体   繁体   中英

Why does this not show the message “Hello world!”?

var div = document.createElement("tempdiv");
div.innerHTML = "<html><body><div id='test'>Hello World!</div></body></html>";
alert(div.getElementById("test").innerHTML);

I get the error " Uncaught TypeError: Object #HTMLUnknownElement has no method 'getElementById' "

The getElementById method only exists on the document object. It is not supported by individual DOM elements. If you were to add the element to the DOM, you could call document.getElementById("test").innerHTML; to get your text.

Elements not in the document are not searched by getElementById. When creating an element and assigning it an ID, you have to insert the element into the document tree with insertBefore or a similar method before you can access it with getElementById.

Ref: https://developer.mozilla.org/en-US/docs/DOM/document.getElementById

Example:

var div = document.createElement("div");
document.body.appendChild(div);
div.innerHTML = "<div id='test'>Hello World!</div>";
console.log(document.getElementById("test"));

Don't forget to set an Id in to the created div to be able to select:

var div = document.createElement("div");
div.setAttribute('id', 'idName');
div.innerHTML = "<html><body><div id='test'>Hello World!</div></body></html>";

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