2

I've noticed that when I am trying to check for a variable within the window object, javascript will return the DOM node of an id matching the variable name. Consider the following code:

<html>
<body>
  <div id='hello'>
  </div>
  <script>console.log(window.hello);</script>
</body>
</html>

In this example, the console will output the DOM object representation of <div id='hello'> and any of its descendants. I've also observed that overwriting window.hello doesn't affect the DOM and subsequent operations show the new assignment.

Is there a way to type check specifically for a DOM object? Alternatively, is there a way to avoid this behavior? Although not difficult, having to be conscious of page ID's when choosing namespaces seems like it could become very counter intuitive.

devnill
  • 2,043
  • 4
  • 21
  • 31
  • possible duplicate of [Javascript isDOM -- How do you check if a Javascript Object is a DOM Object?](http://stackoverflow.com/questions/384286/javascript-isdom-how-do-you-check-if-a-javascript-object-is-a-dom-object) – Daniel A. White Dec 13 '13 at 20:53
  • 1
    My question was less about they type checking and more about the nature of javascript returning a DOM node when attempting to access an undefined variable. – devnill Dec 13 '13 at 21:05

2 Answers2

2

Some browsers will create a global variable for each id value in the document. In general, you should use:

document.getElementById("hello")

to retrieve DOM elements by id.

This is yet another reason why you should generally avoid using the global namespace any more than required as it is significantly polluted by this browser practice.


If you really want to test whether something is DOM object, you can see how that is done here: JavaScript isDOM -- How do you check if a JavaScript Object is a DOM Object?, but you should, in general, not need to do this for regular DOM programming purposes.

Community
  • 1
  • 1
jfriend00
  • 683,504
  • 96
  • 985
  • 979
1

This is actually the HTML5 standard:

http://www.whatwg.org/specs/web-apps/current-work/#named-access-on-the-window-object

A way to be safe about this is to make all your javascript objects and functions within a "namespace":

var objs = {

    someObject: document.getElementById( "someThing" ),

    someFunction: function() {},

    hello: {
        ...
    }
};

//Now you can access it without interfering with the DOM "hello"
console.log( window.objs.hello );
Don Rhummy
  • 24,730
  • 42
  • 175
  • 330