Contents

[JS]為什麼能用document.form1.username呢?

為什麼能用document.form1.username這個東西?

這個困擾我很久…,在這公司這幾年
常常看到舊的code,從不解用成習慣
同事也不知道為什麼,古早人都是這樣寫
之前有找,但沒有找到相關資訊…
今天花一些時間找到資料,終於找到為什麼

平常見網路教使用document.form1.elements['username']document.forms['form1'].elements['uername'].
公司常見寫法document.form1.username,只知道form1是用name不是用id去命名的
一直思考到今日,我又繼續查

JavaScript Properties

今天爬到物件的使用 - JavaScript | MDN這篇

The exception to this rule is objects reflected from HTML, such as the forms array. You can always refer to objects in these arrays by either their ordinal number (based on where they appear in the document) or their name (if defined). For example, if the second tag in a document has a NAME attribute of “myForm”, you can refer to the form as document.forms[1] or document.forms[“myForm”] or document.myForm.

當下嘗試寫下面code

1
2
3
4
var a = [];
a['length'];
//return 0
//常見的a.length

竟然能work

看到這篇我晃然大悟…

今天我終於還債了,開心:D

簡單深入了解

document.forms傳回HTMLCollection東西
HTMLCollection在W3C文件可以看見

element = collection[name]
Returns the first element with ID or name name from the collection.

DOM Standard

所以document.forms.(name)document.forms.(id)都可以抓到

做到這邊我發現怪怪的…
document.(form1)怎麼可以抓到name,但不能抓到ID
不過先排除HTMLCollection一樣問題

直接找W3C文件Document文件Named elements

  1. Exposed embed, form, iframe, img, or exposed object elements that have a name content attribute whose value is name, or
  1. Exposed object elements that have an id content attribute whose value is name, or
  1. img elements that have an id content attribute whose value is name, and that have a non-empty name content attribute present also.
  1. An embed or object element is said to be exposed if it has no exposed object ancestor, and, for object elements, is additionally either not showing its fallback content or has no object or embed descendants.

看了文件驚呆了,原來不是只有name會抓,object的id也會抓,還有img有id跟name的時候,才會在document.(id)出現
WTF這什麼鬼?! 不過文件規定是這樣應該就沒錯了…,不知道這樣設計是運用在什麼地方
至少不會再踩到雷了吧XD

再來是Form文件HTML Standard
id跟name都能吃到,詳細就自己去看

20180124 發現window也跟document一樣有帶有屬性[HTMLCollection]

難怪平常看到form1,可以正常跑,是因為抓到window變數
突然恍然大悟,window.(id)可以抓到我設定的


BTW

其實找超久的,原本從MDN裡的document,form手冊看
沒有看到我要的,我又從W3C找有沒有相關內容
結果還是沒有…,不過好在爬到MDN物件的使用 - JavaScript | MDN這篇
為什麼許多教學文不會教document.form1.username?

因為這都是JavaScript裡基礎的東西

看到都快要去跪鍵盤了orz

參考來源:
JavaScript Properties
HTMLCollection - Web APIs | MDN
[筆記]用javascript來取得表單元素內容的值(javascript取值) ~ PJCHENder那些沒告訴你的小細節