webmat
webmat

Reputation: 60666

Can an HTML element have multiple ids?

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.

Upvotes: 372

Views: 499010

Answers (21)

golden mango
golden mango

Reputation: 1

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

Upvotes: -1

bawumbu
bawumbu

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

Upvotes: 0

willy wonka
willy wonka

Reputation: 1686

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>

Upvotes: 0

Ross
Ross

Reputation: 47077

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.

Upvotes: 25

Samdom For Peace
Samdom For Peace

Reputation: 49

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>

Upvotes: 2

Agboola Feyikemi
Agboola Feyikemi

Reputation: 19

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.

Upvotes: -1

corysimmons
corysimmons

Reputation: 7695

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.

Upvotes: 3

Snowcrash
Snowcrash

Reputation: 86387

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

Upvotes: 2

user3266067
user3266067

Reputation:

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>

Upvotes: 0

Alexandr
Alexandr

Reputation: 474

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.

Upvotes: 2

James
James

Reputation: 41

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>

Upvotes: 3

Taylor
Taylor

Reputation: 1800

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.

Upvotes: 1

AmbroseChapel
AmbroseChapel

Reputation: 12097

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.

Upvotes: 21

acrosman
acrosman

Reputation: 12900

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

Upvotes: 27

tpower
tpower

Reputation: 56906

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.

Upvotes: 4

user123444555621
user123444555621

Reputation: 153284

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.

Upvotes: 226

timmow
timmow

Reputation: 3625

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.

Upvotes: 235

Ole Reidar Johansen
Ole Reidar Johansen

Reputation: 21

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 :(

Upvotes: -2

Anjisan
Anjisan

Reputation: 1799

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

Upvotes: 3

tvanfosson
tvanfosson

Reputation: 532765

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.

Upvotes: 23

Robert K
Robert K

Reputation: 30328

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.

Upvotes: 0

Related Questions