Michel
Michel

Reputation: 4157

console.log returns html element if variable not exists

I'm totally confused about the behavior of console.log() when outputting a non-existing variable.

I was accidentally logging a non-existing variable bon. But the console didn't show "undefined" as expected, but <div id="bon">.

Searching where the variable was set (as I didn't set it and it had to be global, as it was popping up inside a function), I stripped all javascript, css and html untill there was nothing left at all:

<!DOCTYPE HTML>
<html> 
<head></head>
<body>
   <div id="bon">a</div>
   <script>
      console.log(bon);
   </script>
</body>
</html>

Testing in Firefox, Chrome, Explorer 11, Edge, Safari they all returned:

< div id="bon">

Changing the script into

<script>
    function foo(){
        console.log(bon);
    }
    foo();
</script>

gave the same result.

Only this

   <script>
      console.log(bon);
      var bon="not bon";
      console.log(bon);
   </script>

gave the expected output:

undefined
not bon

Am I missing something or does this mean the console just returns an element from the DOM with the same id if it can't find the variable itself?

Edit

As Chris G pointed out, the answer is found here. It turns out nowadays one can use id's to reference HTML elements in the global space without assigning them to a var=. But also: it is not recommended to do so.

Upvotes: 2

Views: 783

Answers (1)

Gopal M
Gopal M

Reputation: 34

This is because you have a Div tag with the same ID and as "bon" has not been initiated anywhere in the Page. So "bon" automtically refers to the Div Tag.

Upvotes: 1

Related Questions