简体   繁体   中英

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?

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 (eg for identifying fields when extracting data from HTML pages into a database, translating HTML documents into other formats, etc.).

link to w3 site

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('...');
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM