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'"

有帮助吗?

解决方案 2

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"));

其他提示

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.

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>";
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top