Can an HTML element have multiple ids? - html

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.

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.

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.

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

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.

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.

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.

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.

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

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>

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.

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.

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

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>Exponential Equations</p>
<p><Logarithmic Expressions</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>

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.

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.

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>

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.

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

Related

How to comment out classes inside class=""? Is this even possible?

Is it possible to comment out specific classes inside the HTML (<div class="" ...>)?
For example:
<div data-group="group1" data-container="true" class="container-lg d-flex /* slider */ p-0">
Where in this example the class "slider" should be (temporarily) excluded from the class list.
[UPDATE]
Based on the comments I understand the way of thinking, so I go for the solution Lee Taylor mentioned. When I want to disable a specific class assignment, I just add a prefix to that class. For example:
<div class="slider container"...
becomes:
<div class="disable-slider container"...
Life could be so easy if the mind is thinking too complex :-D
Thank you all for thinking with me!
[/UPDATE]
This would make life a lot easier, in my opinion, in these ways:
You don't have to switch to your style sheet and go searching for the matching class, commenting out and switch back again to the code.
It's clear for everyone that you just exclude the complete function, which - if named clearly - gives other developers a better overview.
For testing purposes you could use this as (style) modules, which are enabled/disabled in a snap! Again, no more hopping between screens/tabs/windows.
Easier debugging. Just comment out some classes and you've got the source of the problem in no time.
It stimulates developers to use recognizable and clearly named classes
Currently I copy the whole element/row, comment this out and add a comment and then paste the copied row below. Then I remove classes from this line of code.
Most of the time this doesn't get updated, so you can't see it as a reliable backup if you're debugging.
I know for sure that such would be possible with JS, but why? (Also changing the HTML structure with JS gives a lot of headaches when it comes to layout shifts and not everyone has the possibility to make use of server side scripting.) Such should exist HTML in my opinion.
Am I the only one who has this in mind?
Per the HTML Specification on the class attribute:
When specified on HTML elements, the class attribute must have a value that is a set of space-separated tokens representing the various classes that the element belongs to.
Here is the definition for space-separated tokens:
A set of space-separated tokens is a string containing zero or more words (known as tokens) separated by one or more ASCII whitespace, where words consist of any string of one or more characters, none of which are ASCII whitespace.
A string containing a set of space-separated tokens may have leading or trailing ASCII whitespace.
Therefore, no, you should technically not be allowed to comment out class list members in any way. If any implementation of the specification does allow this, then it is undefined behavior and should not be depended upon.

Multiple "style" attributes in a "span" tag: what's supposed to happen?

Consider the following HTML fragment with two style attributes:
<span style="color:blue" style="font-style:italic">Test</span>
In Opera 12.16 and Chrome 40, it shows up as blue non-italic text, while Internet Explorer 9 shows blue italic text. What, if anything, does the standard say is supposed to show up?
Separate your rules with a semi colon in a single declaration:
<span style="color:blue;font-style:italic">Test</span>
In HTML, SGML and XML, (1) attributes cannot be repeated, and should only be defined in an element once.
So your example:
<span style="color:blue" style="font-style:italic">Test</span>
is non-conformant to the HTML standard, and will result in undefined behaviour, which explains why different browsers are rendering it differently.
Since there is no defined way to interpret this, browsers can interpret it however they want and merge them, or ignore them as they wish.
(1): Every article I can find states that attributes are "key/value" pairs or "attribute-value" pairs, heavily implying the keys must be unique. The best source I can find states:
Attribute names (id and status in this example) are subject to the same restrictions as other names in XML; they need not be unique across the whole DTD, however, but only within the list of attributes for a given element. (Emphasis mine.)

In page anchors with spaces in the title

I have a page with some <h1 name="Header Name"> tags. Notice that the name attribute has a space in it. I want to use an anchor so that I can jump to the heading. I thought that if I added %20 to replace the spaces it would work, but no.
I am currently swamped, so would prefer not to edit the source and redeploy with each header having an ID or title with hyphens instead of spaces.
<!-- non-working example of what I want -->
<a href="mypage.html#Header%20Name" />
<h1 title="Header Name">Foo</h1>
I read through the spec here, but couldn't find an answer. I also could not find an answer via Google or SO.
http://www.w3.org/TR/html4/struct/links.html
Is there a way to do this?
That's not how anchor tags work. You can jump to a name of an anchor tag, or an id of any element. You can never jump to a title attribute, unfortunately. You would need to modify the html, which you don't want to do, or include javascript to accomplish what you are asking.
Edit: Standards have always said id attributes cannot include spaces, including HTML5, which says this:
HTML5 gets rid of the additional restrictions on the id attribute. The
only requirements left — apart from being unique in the document — are
that the value must contain at least one character (can’t be empty),
and that it can’t contain any space characters.
Here's the W3C spec https://www.w3.org/TR/REC-html40-971218/types.html#h-6.2
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 (".").
No spaces.
Anchors point to name or id attributes. It won't find your title attribute.
Use <h1 id="Header Name"> and it should work, but ideally you shouldn't have spaces there.
The destination anchor should be defined by an id attribute, and it must not contain a space. (HTML5 removes all other constraints but disallows a space and an empty value. Older HTML versions are much more restrictive.) So:
<h1 id="HeaderName">Foo</h1>
Alternatively, you could use an a element with name attribute, but this is clumsy and outdated (and forbidden in HTML5, though it still works, properly used):
<h1><a name="HeaderName">Foo</a></h1>
You can use the name attribute on a few elements only, not e.g. in h1, and only in a elements does it have the meaning of acting as a destination anchor.
The title attribute can be used on any element (at least as per HTML5), but it is merely an advisory title and has nothing to do with linking.
The construct <a href="mypage.html#Header%20Name" /> denotes an empty a element, a usability nightmare, and does not actually work (it is taken just as a start tag of an element), except in XHTML when served with an XML document type, which you are most probably not doing. So just don’t use the “self-closing” syntax except for elements with empty declared content, if at all.
There /is/ a way to have an anchor with a space in its name without violating the HTML specification. Use <a name="my%20name%20with%20spaces"></a>. The specification makes it clear that you can use percent-encoding when using <a> with the name attribute. However, when using id, you should not percent-encode the attribute, and since spaces are disallowed in the id attribute, the only option is to use <a name=...> instead.
More information: https://blog.markasoftware.com/post/spaces-in-anchor-names/

ID and class attributes in HTML5

"The id attribute got more classy in HTML5" is written at some pages. If I use class attribute instead of id, does it conform to HTML5? Thanks for your help.
I believe you're talking about this article. Well, nothing has really changed — classes and ids are used the same way as in HTML4.
Except one thing: The HTML4 spec says the following
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 (“.”).
However, in the HTML5 spec, the requirement for ids is much less rigid
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.
So HTML5 ids can accept more characters, which is what the article you're reffering to is talking about.
The attributes still have two different purposes:
class can contain multiple classes and multiple elements can have the same classes
id contains a single ID and that ID can only be used for one element.
The statement you quoted exists because some restrictions on how an ID must look like have been lifted in HTML5 - classes never had those restrictions.
The difference between ID and class is that the ID has to be unique at one page but the class can be used multiply times.
Both is valid HTML 5, you can validate your page here: http://validator.w3.org/
Nothing has really changed with HTML5 in that respect. IDs are still unique, and classes can be shared across elements. Not sure what the quote was referring to.
class is for generic purpose and id is for unique identification purpose. I mean, id uniquely identifies an element and class specifies a group elements to have the same type of behavior. I hope, it clears the prupose of class and id.

What's the point of HTML forms `name` attribute?

What's the point of the name attribute on an HTML form? As far as I can tell, you can't read the form name on submission or do anything else with it. Does it serve a purpose?
In short, and probably oversimplifying a bit: It is used instead of id for browsers that don't understand document.getElementById.
These days it serves no real purpose. It is a legacy from the early days of the browser wars before the use of name to describe how to send control values when a form is submitted and id to identify an element within the page was settled.
From the specification:
The name attribute represents the form's name within the forms collection.
Once you assign a name to an element, you can refer to that element via document.name_of_element throughout your code. It doesn't work to tell when you've got multiple fields of the same name, but it does allow shortcuts like:
<form name="myform" ...>
document.myform.submit();
instead of
document.getElementsByName('myform')[0].submit();
Here's what MDN has to say about it:
name
The name of the form. In HTML 4, its use is deprecated (id should be used instead). It must be unique among the forms in a document and not just an empty string in HTML 5.
(from <form>, Attributes, name)
I find it slightly confusing that specifies that it must be unique, non-empty string in HTML 5 when it was deprecated in HTML 4. (I'd guess that requirement only applies if the name attribute is specified at all?). But I think it's safe to say that any purpose it once served has been superseded by the id attribute.
You can use the name attribute as an "extra information" attribute - similarly as with a hidden input - but this keeps the extra information tied into the form, which makes it just a little simpler to read/access.
name attribute is not completely redundant vis-à-vis id. As aforementioned, it useful with <forms>, but less known is that it can also be used with with any HTMLCollection, such as the children property of any DOM element.
HTMLCollection, in additional to be a array-like object, will have named properties commensurate with any named members (or the first occurrence in case of non-unique name). It is useful to retrieve specific named nodes.
For example, in the following example HTML:
<div id='person1'>
<span name='firstname'>John</span>
<span name='lastname'>Doe</span>
<span name='middlename'></span>
</div>
<div id='person2'>
<span name='firstname'>Jane</span>
<span name='lastname'>Doe</span>
<span name='middlename'></span>
</div>
by naming each child, one can quickly and efficiently retrieve a named element, such as lastname, as such:
document.getElementById('person1').children.namedItem('lastname')
...and if there is no risk of 'length' being the name of a member element, (being that length is a reserved property of HTMLCollection), a more terse notation may be used instead:
document.getElementById('person1').children.lastname
DOM Living Standard 2019 March 29
An HTMLCollection object is a collection of elements...
The namedItem(key) method, when invoked, must run these steps:
If key is the empty string, return null.
Return the first element in the collection for which at least one of the following is true:
it has an ID which is key;
it is in the HTML namespace and has a name attribute whose value is key;