简体   繁体   English

为什么它没有显示消息“ Hello world!”?

[英]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' " 我收到错误“ 未捕获的TypeError:对象#HTMLUnknownElement没有方法'getElementById'

The getElementById method only exists on the document object. getElementById方法仅存在于文档对象上。 It is not supported by individual DOM elements. 单个DOM元素不支持它。 If you were to add the element to the DOM, you could call document.getElementById("test").innerHTML; 如果要将元素添加到DOM,则可以调用document.getElementById("test").innerHTML; to get your text. 得到您的文本。

Elements not in the document are not searched by getElementById. 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. 创建元素并为其分配ID时,必须先使用insertBefore或类似方法将元素插入文档树中,然后才能使用getElementById访问它。

Ref: https://developer.mozilla.org/en-US/docs/DOM/document.getElementById 参考: https : //developer.mozilla.org/zh-CN/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: 不要忘记为创建的div设置ID,以便选择:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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