zneak
zneak

Reputation: 138161

What is the standard error behavior when multiple elements share the same id?

I'm working on automated tests with Selenium for a complex, enterprise-grade web app, and I ran into some problems.

It seems the programmers don't hold standard HTML too high in their priority. Pages aren't compliant at all. My current problem is that several elements share the same id value, which, obviously, isn't a good thing. I'm not allowed to change it, and anyways I don't think I would like to.

What happens when many elements have the same id? How do popular browsers handle that? I'm especially asking in the case of document.getElementById: which one is returned?

Upvotes: 1

Views: 384

Answers (2)

Mutation Person
Mutation Person

Reputation: 30520

Unless there is something internal to document.getElementId that I am not privy to, I would expect it to return the first element it encounters. (See this fiddle: http://jsfiddle.net/rrTra/)

Although browser behaviours may vary, I believe most will ignore the other entries without reporting an error.

EDIT

Found this link: http://reference.sitepoint.com/javascript/Document/getElementById

When multiple elements share the same ID

The behavior of this method when more than one element of the specified ID exists is not standardized, because a document is not allowed to contain more than one element with the same ID. But for reference, in this situation all browsers return the first element found.

Upvotes: 1

Floern
Floern

Reputation: 33904

document.getElementById returns the first element with the id

tested in FF, IE, Chrome, Safari & Opera

Upvotes: 1

Related Questions