drake035
drake035

Reputation: 2887

Several HTML elements having same ID, is it so wrong?

In some DIV element, I have a complicated layout with different sub-elements having their own IDs. Today I realize I need to duplicate the whole thing and I have no time to recreate the same with different IDs.

Is it so bad to have two DIV with the same ID for example? What can happen?

Upvotes: 0

Views: 97

Answers (3)

Rich Bradshaw
Rich Bradshaw

Reputation: 72975

The main issue is that when selecting them using JS it's assumed that there will only be one of each ID – that means things typically break.

Specifically, getElementById is very fast, as it assumes only one of each id.

Additionally, the HTML4 specification says:

This attribute assigns a name to an element. This name must be unique in a document.

It's really not very hard to change, just swap id to class, and in your CSS # to ..

Upvotes: 2

aorcsik
aorcsik

Reputation: 15552

It is bad, really, since it should not be used like that.

Browsers are quite forgiving, but I would take the time to avoid this, using classes.

Upvotes: 0

Thanakron Tandavas
Thanakron Tandavas

Reputation: 5683

An ID should be unique (only one element uses it), while class is more like universal (group of elements use it).

Quote from this website, think of it as a classroom:

  • ID = A person's Identification (ID) is unique to one person.
  • Class = There are many people in a class.

So, I suggest you change from ID to class.

Upvotes: 0

Related Questions