Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is it a bad thing to have multiple HTML elements with the same id attribute?

Tags:

html

Why is it bad practice to have more than one HTML element with the same id attribute on the same page? I am looking for a way to explain this to someone who is not very familiar with HTML.

I know that the HTML spec requires ids to be unique but that doesn't sound like a convincing reason. Why should I care what someone wrote in some document?

The main reason I can think of is that multiple elements with the same id can cause strange and undefined behavior with Javascript functions such as document.getElementById. I also know that it can cause unexpected behavior with fragment identifiers in URLs. Can anyone think of any other reasons that would make sense to HTML newbies?

like image 980
Elias Zamaria Avatar asked Sep 21 '11 19:09

Elias Zamaria


Video Answer


2 Answers

Why should I care what someone wrote in some document?

You should care because if you are writing HTML, it will be rendered in a browser which was written by someone who did care. W3C created the spec and Google, Mozilla, Microsoft etc... are following it so it is in your interest to follow it as well.

like image 106
Dennis Avatar answered Oct 20 '22 16:10

Dennis


You basicaly responded to the question. I think that as long as an elemenet can no longer be uniquely identified by the id, than any function that resides on this functionality will break. You can still choose to search elements in an xpath style using the id like you would use a class, but it's cumbersome, error prone and will give you headaches later.

like image 33
Dan Bizdadea Avatar answered Oct 20 '22 17:10

Dan Bizdadea