简体   繁体   English

为什么document.write和console.log为getElementById提供不同的输出?

[英]Why does document.write and console.log give different outputs for getElementById?

var myListItems = document.getElementById ("li");
function myList () {console.log (myListItems)};
function myWrist () {document.write (myListItems)};
myList();
myWrist();

For the JavaScript above, why does document.write output - [object HTMLLIElement] , whereas console.log outputs <li id="li">fdsf</li> ? 对于上述JavaScript,为什么document.write输出- [object HTMLLIElement] ,而console.log输出<li id="li">fdsf</li>

Any help would be appreciated.. 任何帮助,将不胜感激..

The console varies depending on browser. 控制台因浏览器而异。 However, most consoles will output the object and its structure if one exists whereas when using document.write it calls toString and then writes the result of that to the page. 但是,大多数控制台将输出对象及其结构(如果存在),而使用document.write时,它将调用toString ,然后将结果写入页面。

That is why you see the object representation in the console, versus the string representation on the page. 这就是为什么您在控制台中看到对象表示形式而在页面上看到字符串表示形式的原因。

 console.log(document.querySelector("li").toString()); 
 <li></li> 

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

相关问题 为什么console.log(document.getElementById(&#39;blah&#39;)))在Chrome中给出不同的日志消息? - Why does console.log(document.getElementById( 'blah' ))) give different log messages in Chrome? 为什么console.log()和document.write()在JavaScript中为二维数组输出不同的结果? - Why does console.log() and document.write() output different results for a two-dimensional array in JavaScript? document.write与console.log不同? - document.write different from console.log? document.write不起作用,但console.log起作用 - document.write doesnt work, but console.log does Console.log与document.write - Console.log vs document.write 为什么console.log运行无限循环直到溢出,而document.write不运行 - Why does console.log run infinite loops until overflow, and document.write not console.log / document.write和alert之间的区别 - difference between console.log / document.write and alert document.write vs console.log vs innerHTML - document.write vs console.log vs innerHTML 为什么console.log(document.body)给出不同的结果? - why does console.log(document.body) give different looking result? 在javavascript提示(),document.write()和console.log()中使用“ +”(加号)和“,”(逗号) - Using the “+” (plus) and the “,” (comma) in javavascript prompt(), document.write() and console.log()
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM