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.

2

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

4 Comments

This is a standard. It's the HTML5 standard, see more in my post: stackoverflow.com/a/20575948/857025
@DonRhummy - OK, I'll retract the part about it not being a standard. Sounds horrible though with automatic global namespace pollution.
I agree. It's a dumb standard. It should be something like window.dom.hello.
@DonRhummy - yep, not sure how that one got through the committee.
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 );

1 Comment

Ah ha! I haven't heard about that feature of HTML5! Thanks for the link!

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.