Several elements with the same ID responding to one CSS ID selector

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:

document.getElementById('red');

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:

document.querySelectorAll('p[id="red"]');

Note however, that this doesn’t work in IE7 and below…

Leave a Comment