374

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.

7
  • 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? Commented Mar 17, 2017 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. Commented Aug 18, 2017 at 17:29
  • This really depends upon the specification quoted (and likely implemented) and context therein. i.e. w3.org/TR/html5/dom.html#the-id-attribute and the older one which indicates "yes"? w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute Commented Oct 24, 2017 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. Commented Aug 14, 2019 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? Commented Sep 15, 2019 at 21:54

20 Answers 20

235

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.

Sign up to request clarification or add additional context in comments.

3 Comments

"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
Depends on the spec you quote I suppose. "This specification doesn't preclude an element having multiple IDs..." w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute
See here where that sentence is removed w3.org/TR/html5/dom.html#the-id-attribute
226

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.

8 Comments

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: w3.org/TR/html401/struct/global.html#h-7.5.2 (for HTML 4)
@tvanfosson: Surprisingly, the HTML4 spec does NOT say that each element can have at most one id. If you look at the HTML5 specs, 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)
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.
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.
This is why you always have to scroll down and read all the threads.
|
28

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

Comments

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.

3 Comments

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

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.

4 Comments

That would break validation though.
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.
Robbing a bank is illegal, a software issue is never illegal. It's that old virtual reality versus actual reality issue again :-P
@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.
21

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.

1 Comment

This worked for me, for use with named anchors (replacing former use of old-school a name" elements on a single line, as in <a name="x"/><a name="y"/>).
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.

1 Comment

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

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.

1 Comment

+1 for providing a link to a spec and addressing the specific question being asked with relevant information (i.e. the id value cannot contain a space, hence, no multiple ids).
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

1 Comment

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

Comments

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>

1 Comment

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

1 Comment

But, if you read tvanfosson's answer, the two IDs clearly differ "enclosing_id_123" != "enclosed_id_123"
1

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>

Comments

1

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

Comments

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.

1 Comment

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

Comments

0

According to the DOM standard, no.

Historically elements could have multiple identifiers e.g., by using the HTML id attribute and a DTD [doctype declaration]. This specification makes ID a concept of the DOM and allows for only one per element, given by an id attribute.

(added bold)

1 Comment

P.S. I might be out of my depth here, so let me know if I'm wrong or I misinterpreted anything.
-1

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>

Comments

-1

Simple test:

<div id="toto" id="titi">text inside toto/titi</div>
<a href="javascript:alert(document.getElementById('toto').innerHTML)">get value of toto</a><br>
<a href="javascript:alert(document.getElementById('titi').innerHTML)">get value of titi</a><br>
  • doesn't work with Chrome (returns toto, but not titi)
  • doesn't work with Edge (returns toto, but not titi) That's the only browsers I have on hand now but presumably others will have a similar behavior and anyway it proves you cannot rely on such a feature.

To be fair it would have been useful to allow multiple ID's (in some rare circumstances), but it is understandable that it is not allowed.

Comments

-3

Easiest Answer == <span id="eg1"></span> <span id="eg2"></span> <span id="eg3"></span> <span id="eg4"></span> etc etc <p>**target text etc**</p> this does not need to be line by line, I just did this for visual aesthetics. Hope this helps

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.