1

I recently found that the javascript code below, works !

function a(){
    alert(myInput.value);
}
<input type="text" value="That`s new to me" id="myInput"/>
<input type="button" onclick="javascript:a();"/>

What is new to me, is the ability to reach and use an input VALUE, without using the getElementById funcion.

Is it common to use this way of coding ? What are the pros and cons of this coding ?

TNX Amitai

Cerbrus
  • 70,800
  • 18
  • 132
  • 147

2 Answers2

1

DOM elements that have an id are automatically added as properties on the window object, with that id as variable name. That's why you can just use myInput.

It's a new feature in the HTML5 spec:

The HTML5 standard specifies that the window object must have a property key whose value is elem if...

  • there is exactly one DOM element elem whose property id has the value key.
  • there is exactly one DOM element elem whose property name has the value key.
    elem's tag must be one of:
    a, applet, area, embed, form, frame, frameset, iframe, img, object.

Source

Personally, I'd advice against using it, as you have "no" control over your variable names that way.

Declare your own variables, "get" the elements yourself, that way you won't have to worry about x possibly being a variable or not.

Community
  • 1
  • 1
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
  • As you pointed in one of the comments in other question, it comes down to the same issue, if we use `var myInput` , then it wont cause problem and when we call for example `myInput="some string"`, variable `myInput` will be used, but if we forget to write `var`, and try to do an assignment to a global variable `myInput`,it will create problems. – Mustafa sabir Jun 23 '14 at 09:28
  • Could the downvoter please explain why? If I made a mistake, or if some of the information in my answer is incorrect, I'd like to learn from it. – Cerbrus Jun 23 '14 at 10:52
  • Thanks everyone for the answers. I also would like to know why the downvote. Will this practice work with all the new browsers ? – user3766773 Jun 23 '14 at 14:24
  • @user3766773: You're welcome :-). If you feel either of the answers does answer your question, please consider [accepting one of them.](http://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work) – Cerbrus Jun 23 '14 at 14:26
0

Wouldn't call this a very good practice. If I saw something requesting inputName.Value where inputName is the Id of your input, I'd automatically assume that it's an object that's declared somewhere, start looking for it and only then consider checking through the DOM.

var input = getElementById('myInput') does the same but can save precious minutes of not having to look for whether it's a variable or not.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
EvilBeer
  • 2,054
  • 2
  • 19
  • 37