MW. MW. - 3 months ago 24
HTML Question

Can an HTML element have the same attribute twice?

I'm considering writing code which produces an HTML tag that could have duplicate attributes, like this:

<div data-foo="bar" class="some-class" data-foo="baz">


Is this legal HTML? Does one of the
data-foo
-values take precendence over the other? Can I count on semi-modern browsers (IE >= 9) to parse it without choking?

Or am I about to do something really stupid here?

Answer

It is not valid to have the same attribute name twice in an element. The authoritative references for this are somewhat complicated, as old HTML versions were nominally based on SGML and the restriction is implied by a normative reference to the SGML standard. In HTML5 PR, section 8.1.2.3 Attributes explicitly says: “There must never be two or more attributes on the same start tag whose names are an ASCII case-insensitive match for each other.”

What happens in practice is that the latter attribute is ignored. Well, future browsers might do otherwise. In the DOM, attributes appear as properties of the element node as well as in the attributes object, so there would be no natural way to store two values.