I am a newbie to javascript, so forgive my naiveté here. I have discovered a behavior that appears to be inconsistent, at least to me. In doing some testing I put in the following two lines of code:
console.log(document.getElementById("errorMessage"));
window.alert(document.getElementById("errorMessage"));
I was fully expecting both to give me the same result, but no, I didn't.
console.log(document.getElementById("errorMessage"));
gave me:
<span id="errorMessage">
whereas
window.alert(document.getElementById("errorMessage"));
gave me the alert window with:
[Object HTMLSpanElement]
Can anyone help me understand why I got different results even though I passed the exact same arguments?
Added note: This is not a duplicate question, for the one referenced above asks which is better, and not what is the difference between the two.
console.log
is allowed to do "whatever the browser developer tools wish to do". As a result, console.log
is only suitable for live debugging and behaves differently in Firefox, Chrome and IE (in IE it will display the same text as the alert).
Now, alert
works consistently because it treats the input as a string and applies the [[ToString]]
conversion as required. On a DOM element - which uses toString()
for the conversion - this is not very exciting, and ends up as the string "[Object blahblah]" as noticed. (I believe the exact text may vary by browser.)
It's easy to get the same behavior with console.log
by forcing the element to a string manually:
console.log("" + document.getElementById("errorMessage"))
However, the inverse is not true and, while it could be somewhat emulated by showing the "outer HTML" in the alert, the console.log
behavior result is simply (wonderful) magic in certain developer tools.
This magic is what allows Chrome to provide "live inspection" of objects (including DOM elements) that are supplied to console.log. However, as mentioned above, IE's console.log (at least up to IE10) also forces the value to a string.. which is not so magical and quite much like the alert.
While alert can be used for "quick debugging", I'd recommend using debugger
, console.log
, and the break-point/exception support provided by the appropriate developer tools as they are much more suited to the task at hand.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With