Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
223 views
in Technique[技术] by (71.8m points)

html - Several elements with the same ID responding to one CSS ID selector

Is it safe to give several elements the same ID in one page? For example this often happens, when using some jquery plugins, when you run some slider or gallery twice or more. We know, developers like to give some ID to the html container in order the script works faster.

Let's read w3.org documentation:

What makes attributes of type ID special is that no two such attributes can have the same value; whatever the document language, an ID attribute can be used to uniquely identify its element.

But the next example with 2 elements having the same ID works fine in all browsers, though it's not valid:

#red {
  color: red;
}
<p id="red">I am a red text.</p>
<p id="red">I am a red text too.</p>
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Browsers always try to "fail silently". What this means is that even though your HTML is invalid, the browser will try to guess what your intent was, and handle it accordingly.

However, deviating from the spec can cause some very unforeseen side effects.

For example:

document.getElementById('red');

will only get you the first one.

You'll also have to test your page in all the browsers that your users might use, to make sure your code works as intended. You can't just assume that it'll work.

In short: Don't do this! If you need to target several elements with the same CSS, use a class name. That's what they were designed for...


Having said that; if you really need to select multiple elements with the same ID, use an attribute selector:

document.querySelectorAll('p[id="red"]');

Note however, that this doesn't work in IE7 and below...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...