Does Id Have to Be Unique in the Whole Page

Does ID have to be unique in the whole page?

Yes, it must be unique.

HTML4:

https://www.w3.org/TR/html4/struct/global.html#h-7.5.2

Section 7.5.2:

id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.

HTML5:

https://www.w3.org/TR/html5/dom.html#element-attrdef-global-id

The id attribute specifies its element's unique identifier (ID). 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.

uniqueness of ID: single page or entire website?

Whilst it is true that it is unique to a given page - take care with this, since you may have a common external CSS sheet or javascript page that is inserted and utilised site wide. Therefore if you are not careful you may inadvertently apply styling or functionality to an element that is unintended - simply because it shares an id with another element on another page. Its absolutely fine to have same id's on each page (and it may be that you want to have the same styling or function applied) - but it may not be that for all instances.

Why are duplicate ID values not allowed in HTML?

Specification says UNIQUE

HTML 4.01 specification says ID must be document-wide unique.

HTML 5 specification says the same thing but in other words. It
says that ID must be unique in its home subtree, which is basically
the document if we read the definition of it.

Avoid duplication

But since HTML renderers are very forgiving when it comes to HTML
rendering they permit duplicate IDs. This should be avoided if at all
possible and strictly avoided when programmatically accessing
elements by IDs in JavaScript. I'm not sure what getElementById
function should return when several matching elements are found?
Should it:

  • return an error?
  • return first matching element?
  • return last matching element?
  • return a set of matching elements?
  • return nothing?

But even if browsers work reliably these days, nobody can guarantee
this behavior in the future since this is against specification.
That's why I recommend you never duplicate IDs within the same
document.

This is an answer by Robert Koritnik at Software Engineering asked by danludwig

Question: Two HTML elements with same id attribute: How bad is it really?

Duplicate ids not allowed in HTML

That code is incorrect. Incorrect doesn't come in shades of grey. This
code violates the standard and is therefore incorrect. It would fail
validation checking, and it should. That said, no browser currently
on the market would complain about it, or have any problem with it at
all. Browsers would be within their rights o complain about it, but
none of the current versions of any of them currently do. Which
doesn't mean future versions might not treat this code badly.

~From Dan Ray

Duplicate ids and JavaScript

So if you use duplicate ids in your HTML many libraries will not work as expected. The most libraries will get the first id they find and return that element. When we look at pure JavaScript: the document.getElementById("idName"); should return in the case of multiple elements with the same id. It says it must return the first element, in tree order.

When to use div id or div classes through an entire website

ID's and classes are not just about uniqueness and duplications. There is something called Specificity in CSS, so if you read more on specificity, it will say that ID declarations have more specificity score than class rules, thus, it is recommended to use classes wherever you can in your CSS and leave ID's for JavaScript actions.

Also, lets be clear here, CSS has nothing to do with ID duplication nor does HTML. It's JavaScript where you will find issues if you duplicate the ID in your HTML(DOM). So technically you can use duplicate ID's as they are just identifiers for that element(though, HTML validation will yell out an error), but it does cause an issue when you start using those ID's in JavaScript. (Now am not saying that you should use duplicate ID's but just clarifying the basics.)

Talking more over specificity,

#something {
color: red;
}

.something {
color: green;
}

<div class="something" id="something">This will be red and not green</div>

So, the more you make use of ID's, the more specific your CSS gets and at certain stage, you need to write even more specific rules to override the previous ones thus creating more messy CSS.


Base rule, use tag selectors wherever you can, atleast to set defaults or resetting those elements, use classes over ID's, leave ID's if you want initiate a particular EVENT or ACTION via JavaScript, for example, a click event on a button. Using ID's in your HTML helps JavaScript process faster as it will stop looking for another element beyond your first matched element.

Can you use the same id once for multiple html page?

An id should only be used once on a single document. It is used for elements that only should appear once on the page anyway (think of a "top navigation bar"). Classes are used for elements that can appear more than once (think of a "particularly styled table", a "repeatable block of information" or things that share particular charasteristics such as "on this browser width this block spans 6 columns" in for example bootstrap). It is perfectly normal to use the same id on different pages. Usually you'll make a skeleton/template for your layout, where each element will be styled the same on each page that uses this template. It is then helpful to have the same id for the same element across different pages. (or: It would be considered sloppy to change the layout of the page on every page, using different id's for each element, as it would be hard or impossible to maintain your pages.)

Html duplicated ID

You absolutely should not have duplicate IDs. It may work*, but it is semantically incorrect and you should not do it

You should restructure your jQuery, however much that may stink. The best option would be to use a class, perhaps using the specific id of the parent to specify which one you want

Another less attractive but viable way would be to add a number or something to the end of the ID to make it unique then use jQuery to detect any elements with a specific part of an ID

* - As Arun describes jQuery will accept the selector, but it is NOT favorable because it is incorrect

What are valid values for the id attribute in HTML?

For HTML 4, the answer is technically:

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

HTML 5 is even more permissive, saying only that an id must contain at least one character and may not contain any space characters.

The id attribute is case sensitive in XHTML.

As a purely practical matter, you may want to avoid certain characters. Periods, colons and '#' have special meaning in CSS selectors, so you will have to escape those characters using a backslash in CSS or a double backslash in a selector string passed to jQuery. Think about how often you will have to escape a character in your stylesheets or code before you go crazy with periods and colons in ids.

For example, the HTML declaration <div id="first.name"></div> is valid. You can select that element in CSS as #first\.name and in jQuery like so: $('#first\\.name'). But if you forget the backslash, $('#first.name'), you will have a perfectly valid selector looking for an element with id first and also having class name. This is a bug that is easy to overlook. You might be happier in the long run choosing the id first-name (a hyphen rather than a period), instead.

You can simplify your development tasks by strictly sticking to a naming convention. For example, if you limit yourself entirely to lower-case characters and always separate words with either hyphens or underscores (but not both, pick one and never use the other), then you have an easy-to-remember pattern. You will never wonder "was it firstName or FirstName?" because you will always know that you should type first_name. Prefer camel case? Then limit yourself to that, no hyphens or underscores, and always, consistently use either upper-case or lower-case for the first character, don't mix them.


A now very obscure problem was that at least one browser, Netscape 6, incorrectly treated id attribute values as case-sensitive. That meant that if you had typed id="firstName" in your HTML (lower-case 'f') and #FirstName { color: red } in your CSS (upper-case 'F'), that buggy browser would have failed to set the element's color to red. At the time of this edit, April 2015, I hope you aren't being asked to support Netscape 6. Consider this a historical footnote.

Unique element ID, even if element doesn't have one

UPDATE: Closures are indeed the answer. So after fiddling with it some more, I figured out why closures were initially problematic and how to fix it. The tricky thing with a closure is you have to be careful when iterating through the elements not to end up with all of your closures referencing the same element. For example, this doesn't work:

for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var button = document.createElement("button");
button.addEventListener("click", function(ev) {
// do something with element here
}, false)
}

But this does:

var buildListener = function(element) {
return function(ev) {
// do something with event here
};
};

for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var button = document.createElement("button");
button.addEventListener("click", buildListener(element), false)
}

Anyway, I decided not to select one answer because the question had two answers: 1) No, there are no internal IDs you can use; 2) you should use closures for this. So I simply upvoted the first people to say whether there were internal IDs or who recommended generating IDs, plus anyone who mentioned closures. Thanks for the help!

Can multiple different HTML elements have the same ID if they're different elements?

No.

Element IDs should be unique within the entire document.



Related Topics



Leave a reply



Submit