Is it safe to give several elements the same ID in one page? For example this often happens, when using some jquery plugins, when you run some slider or gallery twice or more. We know, developers like to give some ID to the html container in order the script works faster.
Let’s read w3.org documentation:
What makes attributes of type ID special is that no two such
attributes can have the same value; whatever the document language, an
ID attribute can be used to uniquely identify its element.
But the next example with 2 elements having the same ID works fine in all browsers, though it’s not valid:
#red {
color: red;
}
<p id="red">I am a red text.</p>
<p id="red">I am a red text too.</p>
Can anybody explain this strange situation?
Browsers always try to “fail silently”. What this means is that even though your HTML is invalid, the browser will try to guess what your intent was, and handle it accordingly.
However, deviating from the spec can cause some very unforeseen side effects.
For example:
will only get you the first one.
You’ll also have to test your page in all the browsers that your users might use, to make sure your code works as intended. You can’t just assume that it’ll work.
In short: Don’t do this! If you need to target several elements with the same CSS, use a class name. That’s what they were designed for…
Having said that; if you really need to select multiple elements with the same ID, use an attribute selector:
Note however, that this doesn’t work in IE7 and below…