Can an html element have multiple ids?

前端 未结 18 2347
天命终不由人
天命终不由人 2020-11-22 07:40

I understand that an id must be unique within an HTML/XHTML page.

My question is, for a given element, can I assign multiple ids to it?

相关标签:
18条回答
  • 2020-11-22 08:13

    Contrary to what everyone else said, the correct answer is YES

    The Selectors spec is very clear about this:

    If an element has multiple ID attributes, all of them must be treated as IDs for that element for the purposes of the ID selector.Such a situation could be reached using mixtures of xml:id, DOM3 Core, XML DTDs, and namespace-specific knowledge.


    Edit

    Just to clarify: Yes, an XHTML element can have multiple ids, e.g.

    <p id="foo" xml:id="bar">
    

    but assigning multiple ids to the same id attribute using a space-separated list is not possible.

    0 讨论(0)
  • 2020-11-22 08:16

    http://www.w3.org/TR/REC-html40/struct/global.html#h-7.5.2

    The id attribute assigns a unique identifier to an element (which may be verified by an SGML parser).

    and

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

    So "id" must be unique and can't contain a space.

    0 讨论(0)
  • 2020-11-22 08:18

    That's interesting, but as far as I know the answer is a firm no. I don't see why you need a nested ID, since you'll usually cross it with another element that has the same nested ID. If you don't there's no point, if you do there's still very little point.

    0 讨论(0)
  • 2020-11-22 08:21

    My understanding has always been:

    • ID's are single use and are only applied to one element...

      • Each is attributed as a Unique Identifier to (only) one single element.
    • Classes can be used more than once...

      • They can therefore be applied to more than one element, and similarly yet different, there can be more than one class (i.e. multiple classes) per element.
    0 讨论(0)
  • 2020-11-22 08:22

    No you cannot have multiple ids for a single tag, but I have seen a tag with a name attribute and an id attribute which are treated the same by some applications.

    0 讨论(0)
  • 2020-11-22 08:23

    No. While the definition from w3c for HTML 4 doesn't seem to explicitly cover your question, the definition of the name and id attribute says no spaces in the identifier:

    ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

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