5

Could someone go into the history/reasons why interacting with form elements using the NAME has gone out of practice and document.getElementById has taken over.

What exactly historically happened that prompted this change and shift.

And finally, has there been a shift or are both still recommended ways of doing things?

Document.getElementById vs  document.form.name

According to some forum discussions document.form.name is not recognized by all browsers. Is this the case? See:

"I've been told in the past that you should not use "document.form_name.element_name" compared to "document.getElementById()", as the first is not recognized by all browsers. "
Roman C
  • 49,761
  • 33
  • 66
  • 176
Menelaos
  • 23,508
  • 18
  • 90
  • 155
  • What is the actual problem? “You should only ask practical, answerable questions based on actual problems that you face.” http://stackoverflow.com/faq – Jukka K. Korpela Apr 13 '13 at 08:17
  • the problem is both ways work but it would be nice to know what is more correct for when writing code. – Menelaos Apr 13 '13 at 08:32
  • Interpreted as a constructive question “which one is more correct”, this is a duplicate (of at least one old question). – Jukka K. Korpela Apr 13 '13 at 11:07

2 Answers2

3

The property NAME is not necessarily unique. For example, radio buttons are grouped by having the same name. Calling getElementByName would return all buttons in the set. ID is meant to be unique. So, to answer your question, each has their place.

x0n
  • 51,312
  • 7
  • 89
  • 111
  • This one really makes sense. Do you know anything about The accessing through NAME not being in HTML DOM specifications so code that uses it cannot be described as standards compliant. I just found http://jibbering.com/faq/notes/form-access/#faShrt which outlines this though I don't know when the document was written and whether it is still valid today. Unless ofcourse I didn't read that statement right. – Menelaos Apr 13 '13 at 01:58
1

name is universally acceptable when accessed as document.forms[name].element[name]. It's supported in IE 5.5, Firefox 0.8, Opera 5, Navigator 4, etc. It's out of fashion because the simplicity of jQuery made people forget about it.

But if an input element has the same name as a property on the form object, then accessing it might not work: e.g.,

<form name="hi" action="/go"><input name="action" value="world">

Should document.hi.action give you "/go" or "[Input value=world]"?

Kernel James
  • 3,752
  • 25
  • 32
  • Looks like you can completely disambiguate by specifically using `.attributes`, as in `document.forms["hi"].attributes["action"].value` and `.elements` `document.forms["hi"].elements["action"]`, and both appear to be within W3C standards. – JayC Apr 13 '13 at 02:29