shunryu111
shunryu111

Reputation: 6533

multiple elements with the same id

i've heard using multiple id attributes is very bad practice but what confuses me is what if the elements are nested like this...

<div id="slideshow1" class="slideshow">
    <div id="left" class="slideshow-arrow"></div>
    <div id="right" class="slideshow-arrow"></div>
</div>
<div id="slideshow2" class="slideshow">
    <div id="left" class="slideshow-arrow"></div>
    <div id="right" class="slideshow-arrow"></div>
</div>

i've made an example with js here and everything seems to work fine..

http://jsfiddle.net/6YPsX/

if they were nested within the same element then unique id's would make sense but do ID's really need to be unique to the whole document?

Upvotes: 1

Views: 984

Answers (3)

Andrew
Andrew

Reputation: 1989

An ID is more than just a way of finding an element, there are other things associated with an ID. The following link should be helpful and provide a greater insight into this. Here are the main points:

The id attribute has several roles in HTML:

  • As a style sheet selector. As a target anchor for hypertext links.
  • As a means to reference a particular element from a script.
  • As the name of a declared OBJECT element.
  • For general purpose processing by user agents (e.g. for identifying fields when extracting data from HTML pages into a database, translating HTML documents into other formats, etc.).

link to w3 site

Upvotes: 3

Tomalak
Tomalak

Reputation: 338148

You can have multiple classes on the same element

<div id="slideshow1" class="slideshow">
    <div class="slideshow-arrow left"></div>
    <div class="slideshow-arrow right"></div>
</div>

CSS

.slideshow-arrow {
    background: none top left no-repeat;
    width: 20px;
    height: 20px;
}
.slideshow-arrow.left {
    background-image: url('...');
}
.slideshow-arrow.right {
    background-image: url('...');
}

Upvotes: 2

Chris Hawkes
Chris Hawkes

Reputation: 12410

It is a bad practice it won't pass W3C validation and it get's even worse when you try to implement JavaScript. Just use a class name instead or give them different id names.

Upvotes: 1

Related Questions