getElementById issue

I was trying to grab the ‘value’ of a form input with document.getElementById and noticed something strange.

This worked fine:

var grab = document.getElementById("name");
grab.value = "enter name here";

This, however, would not work:

var name = document.getElementById("name");
name.value = "enter name here";

The problem seems to be that if the variable has the same name as the ID, it won’t work. Does anyone know why this is? I looked in my JS reference book and on MDN but could not find the answer.

Thanks!

Some browsers automatically map some fields from the HTML into corresponding globval variables in the JavaScript.

The solution is to avoid using global variables in JavaScript by enclosing your script in an anonymouse self executing function.

(function() {
// put your JavaScript here
})();

to make a variable restricted to a function use this.name. You can also declare global variables within a function with window.name - “name” being the variable name.