Can an HTML element have the same attribute twice?

前端 未结 2 1533
半阙折子戏
半阙折子戏 2020-11-27 21:32

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

相关标签:
2条回答
  • 2020-11-27 21:56

    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.

    0 讨论(0)
  • 2020-11-27 21:57

    It's not technically valid, but every browser will ignore duplicate attributes in HTML documents and use the first value (data-foo="bar" in your case).

    Using the same attribute name twice in a tag is considered an internal parse error. It would cause your document to fail validation, if that's something you're worried about. However, it's important to understand that HTML 5 defines an expected result even for cases where you have a "parse error". The parser is allowed to stop when it encounters an error, but if it chooses not to stop it must produce a specific result described in the specification. In practice, no browsers choose to stop when encountering errors in HTML documents (XML/XHTML is a different matter), so all modern browsers will handle this case successfully and consistently.

    The WHATWG HTML specification describes this case in section 12.2.4.33 "Attribute name state":

    When the user agent leaves the attribute name state (and before emitting the tag token, if appropriate), the complete attribute's name must be compared to the other attributes on the same token; if there is already an attribute on the token with the exact same name, then this is a parse error and the new attribute must be dropped, along with the value that gets associated with it (if any).

    See also its description of "parse error" from the opening of section 12.2 "Parsing HTML documents":

    Certain points in the parsing algorithm are said to be parse errors. The error handling for parse errors is well-defined (that's the processing rules described throughout this specification), but user agents, while parsing an HTML document, may abort the parser at the first parse error that they encounter for which they do not wish to apply the rules described in this specification.

    0 讨论(0)
提交回复
热议问题