HTMLタグで属性が重複したときの挙動について

  • このエントリーをはてなブックマークに追加

次のタグのように属性が重複している場合、パーサーはどのように処理されるのだろうか。
もともと、Nokogiriを使ってパースしていて属性が取れないぞとなって調べたのでメモ。

<div id="s" class="a" class="b"></div>

結論から言うと、先に出現した属性が優先され、後続の重複した属性は無視されます。
Firefox, Chrome, Gumbo-parser, Nokogiri(sax-parser)などで確認しました。

仕様

WHATWGの仕様はこちらにあります。

There must never be two or more attributes on the same start tag whose names are an ASCII case-insensitive match for each other.

https://html.spec.whatwg.org/multipage/syntax.html

仕様的に、2回以上含めることはパースエラーとなる。

This error occurs if the parser encounters an attribute in a tag that already has an attribute with the same name. The parser ignores all such duplicate occurrences of the attribute.

https://html.spec.whatwg.org/#parse-error-duplicate-attribute

しかし、現実的にパースエラーにすると色々と困るので、エラーとして停止する/しないを選択することができ、殆どのブラウザはHTML(not XMLを解釈する時には、重複属性の時は最初の値を採用し、後続に出現した重複属性は無視をする、という選択をしているようです。

参考