CPC
CPC

Reputation: 181

Is it possible for an html5 document to have two ids?

I was wondering if an html5 element can have two ids, like this:

<button id="thing1" id="thing2" name="Button1" onclick="change()">Click here</button>

or this:

<button id="thing1, thing2" name="Button1" onclick="change()">Click here</button>

also, if one of the ids said one thing, and the other id said another thing, which one would be used?

Upvotes: 1

Views: 119

Answers (2)

elixenide
elixenide

Reputation: 44831

TL;DR: No.


In all versions of HTML, each element can have only one id. See the spec:

The id attribute specifies its element's unique identifier (ID). [DOM]

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

Note: There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.

Note: An element's unique identifier can be used for a variety of purposes, most notably as a way to link to specific parts of a document using fragment identifiers, as a way to target an element when scripting, and as a way to style a specific element from CSS.

Identifiers are opaque strings. Particular meanings should not be derived from the value of the id attribute.

In the examples you gave, the parser would read only the first id. If you tried this:

<button id="thing1,thing2" name="Button1" onclick="change()">Click here</button>

(with no space in the id), you would still only have a single id, which would include the comma: thing1,thing2.


Note: there are no reasons why you would want two id values that are not good candidates for using a class or storing the data in some other way. For example, in jQuery, you can do $('#some_id').data('foo', 'bar'); to save a piece of data named foo with the value bar and associate it with the element with id some_id. Classes and data storage are generally much more flexible than ids, anyway.

Edit: Keep in mind that classes aren't only for CSS. You can do <button id="thing1" class="thing2 thing3 thing42"...> and use javascript (either plain or using a library like jQuery) to access the button by one or more of its classes. The class names can be unique to the item and don't have to be used elsewhere or mentioned in your CSS files.

Here's a link to a jsFiddle example of how powerful classes and ids can be when used together.

Upvotes: 5

TheYaXxE
TheYaXxE

Reputation: 4294

Short answer: No

You should use the class-attribute instead.

Upvotes: 2

Related Questions