367

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

For a given element, can I assign multiple ids to it?

<div id="nested_element_123 task_123"></div>

I realize I have an easy solution with simply using a class. I'm just curious about using ids in this manner.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
webmat
  • 58,466
  • 12
  • 54
  • 59
  • I'm programming nearly for a while in html css and js I frequently have the need to use multiple classes but I really never use neither I have the need to use multiple IDs. Nevertheless I'm a bit curious: may I ask what is the situation you faced in such occasion to need multiple IDs? – willy wonka Mar 17 '17 at 20:56
  • 1
    In the rare scenario when one doesn't have access to the source HTML (e.g when building proxies) if you need to target an element that has multiple ids the css selector [id="one two three"'] should target the element. – JisuKim82 Aug 18 '17 at 17:29
  • This really depends upon the specification quoted (and likely implemented) and context therein. i.e. https://www.w3.org/TR/html5/dom.html#the-id-attribute and the older one which indicates "yes"? https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute – Mark Schultheiss Oct 24 '17 at 13:18
  • 1
    @willywonka I know this is like 2+ years later, but I ran into this article just now searching for an answer to this, and felt like sharing the scenario with you I came across, since you never got an answer. I'm doing a project for freecodecamp to create a JS calculator. They want the id for the output to be "display" so they can run their tests against it but I'm creating a scientific calculator with 2 displays: #input and #output, so the #input display ALSO needs the "display" id value in addition to the value of "input" I want to give it for consistency. – Tara Aug 14 '19 at 21:49
  • 1
    Hi **@TaraStahler** you are welcome. As far as I know the browser will only render the first one if you use the notation <... id="input" id="display" ...> and also an id must not contain white spaces (nor tabs) so the notation <...id="input display" ...> isn't valid at all. Just experimented with javascript with the Chrome console and it returns "Uncaught ReferenceError: display is not defined" in both cases. Only the first case returns the object if I get it with the first id, the second is not achievable. In the second case none of the ids is achievable. Maybe you need to refactor your code? – willy wonka Sep 15 '19 at 21:54
  • There is never any need for multiple ids on the same tag since every id is a unique identifier to uniquely identify that specific tag. But you can use multiple classes or even the data- attribute as follows: <... id="input" data-id="display" ...>. – willy wonka Sep 15 '19 at 22:07
  • @willywonka 2023 : Another scenario where multiple IDs was needed for me is that I used a template PHP file for my sprite SVGs and needed to attribute multiples IDs to ONE SVG symbol instead of duplicating the code. – maiakd Mar 28 '23 at 12:00

19 Answers19

233

No. From the XHTML 1.0 Spec

In XML, fragment identifiers are of type ID, and there can only be a single attribute of type ID per element. Therefore, in XHTML 1.0 the id attribute is defined to be of type ID. In order to ensure that XHTML 1.0 documents are well-structured XML documents, XHTML 1.0 documents MUST use the id attribute when defining fragment identifiers on the elements listed above. See the HTML Compatibility Guidelines for information on ensuring such anchors are backward compatible when serving XHTML documents as media type text/html.

ThinkingStiff
  • 64,767
  • 30
  • 146
  • 239
timmow
  • 3,595
  • 2
  • 23
  • 22
  • 7
    "fragment identifiers are of type ID, and there can only be a single attribute of type ID per element." It says here, single attribute and attribute is different from attribute's values. It doesn't say whatever that attribute values should not in any context assumes multivalued either through space separated or any character separation. Though in the specification it says that for backward compatibility it must not contain space character in attributes values Fragment Identifiers(w3.org/TR/xhtml1/#guidelines) So if you want to express multivalued IDs you have to express it differently – Richeve Bebedor Apr 28 '13 at 13:05
  • 4
    Depends on the spec you quote I suppose. "This specification doesn't preclude an element having multiple IDs..." https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute – Mark Schultheiss Oct 24 '17 at 13:02
  • See here where that sentence is removed https://www.w3.org/TR/html5/dom.html#the-id-attribute – Mark Schultheiss Oct 24 '17 at 13:15
224

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
user123444555621
  • 148,182
  • 27
  • 114
  • 126
  • 4
    Unfortunately it's not the CSS specification that's operative here. For HTML/XHTML, you have to look at that spec and the spec there definitely says that each element can have at most one id and that id has to be unique on the page: http://www.w3.org/TR/html401/struct/global.html#h-7.5.2 (for HTML 4) – tvanfosson May 18 '11 at 18:02
  • 11
    @tvanfosson: Surprisingly, the HTML4 spec does NOT say that each element can have at most one id. If you look at [the HTML5 specs](http://dev.w3.org/html5/spec-LC/elements.html#the-id-attribute), you'll even find that `This specification doesn't preclude an element having multiple IDs, if other mechanisms (e.g. DOM Core methods) can set an element's ID in a way that doesn't conflict with the id attribute.` (which corresponds to the CSS specs) – user123444555621 May 18 '11 at 20:57
  • 1
    you can only have one id attribute and the format of the id attribute content precludes having any spaces. In the context of the question -- giving an element 2 "HTML" ids -- it's not possible to do this in either HTML 4 or HTML 5. You're making an assumption that giving it an id that works with CSS is sufficient for what he's trying to do, and it may be that having an xmlid would work, but I don't see how you get that out of the question as written. The example he shows won't work in either HTML 4 or HTML 5 and there's no way to make it work to accomplish what is shown. – tvanfosson May 18 '11 at 21:50
  • @tvanfosson: You're absolutely right in that it can't be done the way the OP asked the question. – user123444555621 May 19 '11 at 06:43
  • 8
    I upvoted this answer as it answers the question: "**can** you **assign** multiple IDs to an element?" However I should add that this goes beyond mere specifications; as shown in the accepted answer, when it comes to HTML/XHTML itself the spec says you may *only* assign an ID using the `id` attribute. To clarify, the `xml:id` attribute (and in fact, any attribute outside the default namespace) is not valid in XHTML. However as you cite from the HTML5 spec, this does not in any way cause `xml:id="bar"` to silently fail; it'll still add the `bar` ID to this element, allowing it to match `#bar`. – BoltClock Jun 18 '12 at 06:37
  • 3
    This is why you always have to scroll down and read all the threads. – Eduardo La Hoz Miranda Mar 14 '14 at 14:24
  • Spec: https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute i.e. "This specification doesn't preclude an element having multiple IDs..." – Mark Schultheiss Oct 24 '17 at 13:01
  • This one does appear to do so: https://www.w3.org/TR/html5/dom.html#the-id-attribute Thus it really depends on the specification quoted. – Mark Schultheiss Oct 24 '17 at 13:16
27

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 (".").

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
acrosman
  • 12,814
  • 10
  • 39
  • 55
25

My understanding has always been:

  • IDs 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.
ctrl-alt-delor
  • 7,506
  • 5
  • 40
  • 52
Ross
  • 46,186
  • 39
  • 120
  • 173
  • 24
    I don't think that this qualifies to be an answer to the question. The question is : "Can multiple IDs be used for a single element?" – Kevin Apr 19 '15 at 10:21
  • 4
    @kevin This answer assumes OP is facing XY problem and can definitely help someone that is trying to achieve the class behaviour via IDs -- for whatever reason. – Mahdi Aug 08 '15 at 09:28
  • You refer to "single use" but that may cause confusion. You can and is a frecuent and correct thing use multiple times one element by its id. What I think you are addressing is another interpretation which is : you sould use one (and only one) id for an element and ONLY for that element. – Mbotet Dec 30 '19 at 09:34
21

No. Every DOM element, if it has an id, has a single, unique id. You could approximate it using something like:

<div id='enclosing_id_123'><span id='enclosed_id_123'></span></div>

and then use navigation to get what you really want.

If you are just looking to apply styles, class names are better.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • That would break validation though. – Aupajo Oct 10 '08 at 23:20
  • 20
    Not me. :-) And I'm not sure what you mean about breaking validation? The ids of the div and span are differing (enclosing vs. enclosed) so there is no issue with duplicate ids. Maybe some people aren't reading very closely. – tvanfosson Oct 12 '08 at 17:35
  • 5
    Robbing a bank is illegal, a software issue is never illegal. It's that old virtual reality versus actual reality issue again :-P – TrojanName May 18 '11 at 15:08
  • @BrianFenton debugging someone elses code made me realize it should be illegal. I say 5 years prison for not following the specs without a good reason not to. – ProblemsOfSumit Jan 10 '14 at 11:38
20

You can only have one ID per element, but you can indeed have more than one class. But don't have multiple class attributes; put multiple class values into one attribute.

<div id="foo" class="bar baz bax">

is perfectly legal.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AmbroseChapel
  • 11,957
  • 7
  • 46
  • 68
4

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tpower
  • 56,100
  • 19
  • 68
  • 100
  • 2
    in IE, before IE8, yes. but they've fixed that bug in standards mode now. getElementById() used to incorrectly return elems matching case insensitively on name and id. – scunliffe Oct 10 '08 at 16:10
3

I'd like to say technically yes, since really what gets rendered is technically always browser-dependent. Most browsers try to keep to the specifications as best they can and as far as I know there is nothing in the CSS specifications against it. I'm only going to vouch for the actual HTML, CSS, and JavaScript code that gets sent to the browser before any other interpreter steps in.

However, I also say no since every browser I typically test on doesn't actually let you.

If you need to see for yourself, save the following as a .html file and open it up in the major browsers. In all browsers I tested on, the JavaScript function will not match to an element. However, remove either "hunkojunk" from the id tag and all works fine.

Sample Code

<html>
<head>
</head>
<body>
    <p id="hunkojunk1 hunkojunk2"></p>

    <script type="text/javascript">
        document.getElementById('hunkojunk2').innerHTML = "JUNK JUNK JUNK JUNK JUNK JUNK";
    </script>
</body>
</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
James
  • 41
  • 1
3

No, you should use nested DIVs if you want to head down that path. Besides, even if you could, imagine the confusion it would cause when you run document.getElementByID(). What ID is it going to grab if there are multiple ones?

On a slightly related topic, you can add multiple classes to a DIV. See Eric Myers discussion at,

http://meyerweb.com/eric/articles/webrev/199802a.html

Anjisan
  • 1,789
  • 3
  • 15
  • 26
  • 3
    Wouldn't it get the id you specify between the parenthesis? `getElementById();` doesn't do anything without a string specifying what to get?! `getElementById('foo');`will get the element with foo as the ID! Multiple IDs wouldn't matter here. It would still look for "foo". – Rin and Len Nov 14 '19 at 12:43
3

Nay.

From 3.2.3.1 The id attribute:

The value must not contain any space characters.

id="a b" <-- find the space character in that VaLuE.

That said, you can style multiple IDs. But if you're following the specification, the answer is no.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
corysimmons
  • 7,296
  • 4
  • 57
  • 65
2

From 7.5.2 Element identifiers: the id and class attributes:

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Alexandr
  • 474
  • 7
  • 13
2

No.

Having said that, there's nothing to stop you doing it. But you'll get inconsistent behaviour with the various browsers. Don't do it. One ID per element.

If you want multiple assignations to an element use classes (separated by a space).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Snowcrash
  • 80,579
  • 89
  • 266
  • 376
2

Any ID assigned to a div element is unique. However, you can assign multiple IDs "under", and not "to" a div element. In that case, you have to represent those IDs as <span></span> IDs.

Say, you want two links in the same HTML page to point to the same div element in the page.

The two different links

<p><a href="#exponentialEquationsCalculator">Exponential Equations</a></p>

<p><a href="#logarithmicExpressionsCalculator"><Logarithmic Expressions</a></p>

Point to the same section of the page

<!-- Exponential / Logarithmic Equations Calculator -->
<div class="w3-container w3-card white w3-margin-bottom">
   <span id="exponentialEquationsCalculator"></span>
   <span id="logarithmicEquationsCalculator"></span>
</div>
  • STOP editing my initial post. It is very correct. Write your own answer to the question instead (make your post and answer the question), or ask questions to my post as comments. Leave my initial post alone. DO NOT edit it. It is very correct. – Samdom For Peace Aug 09 '21 at 02:20
  • You can verify my post by visiting my website: www.exponents-logarithms.appspot.com – Samdom For Peace Aug 09 '21 at 02:26
1

The simple answer is no, as others have said before me. An element can't have more than one ID and an ID can't be used more than once in a page. Try it out and you'll see how well it doesn't work.

In response to tvanfosson's answer regarding the use of the same ID in two different elements. As far as I'm aware, an ID can only be used once in a page regardless of whether it's attached to a different tag.

By definition, an element needing an ID should be unique, but if you need two ID's then it's not really unique and needs a class instead.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Taylor
  • 1,700
  • 4
  • 17
  • 18
  • 1
    But, if you read tvanfosson's answer, the two IDs clearly differ "enclosing_id_123" != "enclosed_id_123" – Ben Dec 07 '10 at 04:44
0

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.

Robert K
  • 30,064
  • 12
  • 61
  • 79
  • 4
    I would have liked using 2 id's as well for backward compatibility. for example something used to be article-8 in an previous version but is now called node-8 having 2 id's of one element would prevent coding a workaround to make it backwards compatible. While both ID's would remain a as unique identifier(s). – FLY Nov 12 '12 at 14:11
0

Classes are specially made for this, and here is the code from which you can understand it:

<html>
<head>
    <style type="text/css">
     .personal{
            height:100px;
            width: 100px;

        }
    .fam{
            border: 2px solid #ccc;
        }
    .x{
            background-color:#ccc;
        }

    </style>
</head>

<body>
    <div class="personal fam x"></div>
</body>
</html>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
0

You can get the element[s] thanks to a partial match by doing something like the following example that shows both querySelctor and querySelctorAll.

In both cases I also have used a selector modified by the * that behaves matching a partial string contained into the id attribute value.

I am using Chrome and both solutions do their job, but about browser compatibility, good programming practice and w3 standards, I can't say.

As you can notice the ids are duplicated and there are also spaces into the id attributes values.

document.querySelector("[id*='123']").innerText = 'the first works';
document.querySelectorAll("[id*='nested']")[1].innerText = 'the second works too';

// But if you try
document.getElementById("[id*='beta']").innerText = 'it does not work';
document.getElementById("#beta]").innerText = 'it does not work';
document.getElementById("#alfa beta nested element_123 task_123]").innerText = 'it does not work';

// none of them will work but get `null` instead and so you get an error in console
<div id="alfa beta nested element_123 task_123"></div>
<div id="alfa beta nested element_123 task_123"></div>
willy wonka
  • 1,440
  • 1
  • 18
  • 31
-1

ID's should be unique, so you should only use a particular ID once on a page. Classes may be used repeatedly.

Check HTML id Attribute (W3Schools) for more details.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-2

I don´t think you can have two Id´s but it should be possible. Using the same id twice is a different case... like two people using the same passport. However one person could have multiple passports... Came looking for this since I have a situation where a single employee can have several functions. Say "sysadm" and "team coordinator" having the id="sysadm teamcoordinator" would let me reference them from other pages so that employees.html#sysadm and employees.html#teamcoordinator would lead to the same place... One day somebody else might take over the team coordinator function while the sysadm remains the sysadm... then I only have to change the ids on the employees.html page ... but like I said - it doesn´t work :(