Question

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

Était-ce utile?

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

Autres conseils

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>";
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top