MW. MW. - 1 year ago 143
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
-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 Source

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 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download