(2017/08/02 20:47追記) 仕様を勘違いしていた為、本文を大幅に変更しました。
required 属性
The accept, alt, max, min, multiple, pattern, placeholder, required, size, src, and step IDL attributes must reflect the respective content attributes of the same name. The dirName IDL attribute must reflect the dirname content attribute. The readOnly IDL attribute must reflect the readonly content attribute. The defaultChecked IDL attribute must reflect the checked content attribute. The defaultValue IDL attribute must reflect the value content attribute.
(意訳)
accept、alt、max、min、multiple、pattern、placeholder、required、size、src、およびstep IDL属性は、同じ名前のそれぞれのコンテンツ属性を反映(reflect)しなければならない(MUST)。
反映(reflect)は後述の「反映型IDL属性 (Reflecting content attributes)」を参照しています。
反映型IDL属性 (Reflecting content attributes)
If a reflecting IDL attribute is a boolean attribute, then on getting the IDL attribute must return true if the content attribute is set, and false if it is absent. On setting, the content attribute must be removed if the IDL attribute is set to false, and must be set to the empty string if the IDL attribute is set to true. (This corresponds to the rules for boolean content attributes.)
(意訳)
反映型IDL属性(Reflecting content attributes)が boolean 属性の場合、IDL属性を取得すると、content属性が設定されている場合はtrueを返し、存在しない場合はfalseを返さなければならない(MUST)。
IDL属性がfalseに設定されている場合はコンテンツ属性を削除し、IDL属性がtrueに設定されている場合は空の文字列に設定しなければならない(MUST)。
(これは boolean content 属性のルールに相当する。)
まとめ
required 属性は「反映型IDL属性 (Reflecting content attributes)」の為、required
プロパティと同様の結果を得ることが出来ます。
ただし、他所からIDL属性が変更された場合は属性値に空文字(falsy)がセットされる為、注意が必要です。
HTML
1<form>
2 <input type="text" />
3 <input type="submit" value="submit" />
4</form>
5<script>
6'use strict';
7var input = document.querySelector('input[type=text]');
8
9console.log(input.getAttribute('required')); // null (required 属性は存在しない)
10console.log(input.attributes.getNamedItem('required')); // null (required 属性は存在しない)
11input.required = true;
12console.log(input.required); // true (反映型IDL属性の規定によって、required 属性が作成され、値は "" になる)
13console.log(input.getAttribute('required')); // "" (required 属性は存在する)
14console.log(input.attributes.getNamedItem('required')); // [object Attr] required="" (required 属性は存在する)
15</script>
つまり、次のコードの評価値は常に等価となります。
JavaScript
1input.required;
2input.getAttribute('required') !== null;
3Boolean(input.attributes.getNamedItem('required'));
if
文に適用すると、次のコードになります。
JavaScript
1// good
2if (input.required) {
3 // 処理
4}
5
6// good
7if (input.getAttribute('required') !== null) {
8 // 処理
9}
10
11// bad
12if (input.getAttribute('required')) {
13 // 処理
14}
15
16// good
17if (input.attributes.getNamedItem('required')) {
18 // 処理
19}
仕様上、getAttribute
や attributes.getNamedItem
で required 属性を参照する事に問題はありません。
が、getAttribute
だけは直観的でない為、直観的でシンプルな required
プロパティが使われる傾向はあると思います。
後は使う人が判断する事になります。
Re: maisumakun さん
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/08/02 10:01
2017/08/02 10:25
2017/08/02 11:49