Reputation: 902
I was inspecting the way a certain webpage alternated between colors in their divs and found this:
<div class="row8 inline clearfix" id="light-orange">...</div>
<div class="row8 inline clearfix" id="light-pink">...</div>
<div class="row8 inline clearfix" id="light-orange">...</div>
<div class="row8 inline clearfix" id="light-pink">...</div>
<div class="row8 inline clearfix" id="light-orange">...</div>
<div class="row8 inline clearfix" id="light-pink">...</div>
<div class="row8 inline clearfix" id="light-orange">...</div>
<div class="row8 inline clearfix" id="light-pink">...</div>
Thinking this was an example of HTML that wouldn’t validate, I ran it through the W3C validator. It did have errors, but none were regarding non-uniqueness of the ids.
Everything I’ve read has stated that ids must be unique within a webpage. What’s the real story here?
Upvotes: 0
Views: 2190
Reputation: 96677
tl;dr: id
must be unique.
When validating this page by directly inputting its HTML, the validator reports an (unrelated) error that stops the reporting of all following errors:
Cannot recover after last error. Any further errors will be ignored.
(I’m not sure why this error is not reported when validating by entering the URI.)
For questions like these (Must id
be unique?), it’s best to check the relevant specification, i.e., HTML5 in your case: The id
attribute
Or you could validate a minimal example, e.g.:
<!DOCTYPE html>
<html>
<head>
<title>@id test</title>
</head>
<body>
<div id="light-orange"></div>
<div id="light-pink"></div>
<div id="light-pink"></div>
</body>
</html>
The W3C validator reports:
1 Error
Duplicate ID light-pink.
Upvotes: 0
Reputation: 6534
Well, if you add <!doctype html>
(as being told here) to that code of yours, you will get an avalanche of Duplicate ID errors (as being told here). Don't worry ;)
Upvotes: 1
Reputation: 22405
HTML 5 specification says that ID must be unique in its home subtree which is basically the document if we read the definition of it.
Found that on google. If you want to alternate colors, use classes. IDs should always be unique.
Upvotes: 1
Reputation: 3879
You should never have duplicate IDs in a webpage because what gets bound or applied to an element by ID will only get applied to the first ID it finds. Hence you will only be applying CSS or binding an event to one of the elements with a given ID. If you have a repeated ID, it probably means that you should be using a class instead.
Upvotes: 1