Can multiple different HTML elements have the same

2018-12-31 01:40发布

Is a scenario like this valid?:

div#foo
span#foo
a#foo

标签: html dom
13条回答
只靠听说
2楼-- · 2018-12-31 01:45

Well, using the HTML validator at w3.org, specific to HTML5, IDs must be unique

Consider the following...

<!DOCTYPE html> 
<html>
    <head>
        <meta charset="UTF-8">
        <title>MyTitle</title> 
    </head>
    <body>
        <div id="x">Barry</div>
        <div id="x">was</div>
        <div id="x">here</div>
    </body>
</html>

the validator responds with ...

Line 9, Column 14: Duplicate ID x.      <div id="x">was</div>
Warning Line 8, Column 14: The first occurrence of ID x was here.       <div id="x">Barry</div>
Error Line 10, Column 14: Duplicate ID x.       <div id="x">here</div>
Warning Line 8, Column 14: The first occurrence of ID x was here.       <div id="x">Barry</div>

... but the OP specifically stated - what about different element types. So consider the following HTML...

<!DOCTYPE html> 
<html>
    <head>
        <meta charset="UTF-8">
        <title>MyTitle</title> 
    </head>
    <body>
        <div id="x">barry
            <span id="x">was here</span>
        </div>
    </body>
</html>

... the result from the validator is...

Line 9, Column 16: Duplicate ID x.          <span id="x">was here</span>
Warning Line 8, Column 14: The first occurrence of ID x was here.       <div id="x">barry

Conclusion:

In either case (same element type, or different element type), if the id is used more than once it is not considered valid HTML5.

查看更多
余欢
3楼-- · 2018-12-31 01:48

I think there is a difference between whether something SHOULD be unique or MUST be unique (i.e. enforced by web browsers).

Should IDs be unique? YES.

Must IDs be unique? NO, at least IE and FireFox allow multiple elements to have the same ID.

查看更多
与君花间醉酒
4楼-- · 2018-12-31 01:52

Nope, IDs have to be unique. You can use classes for that purpose

<div class="a" /><div class="a b" /><span class="a" />

div.a {font: ...;}
/* or just: */
.a {prop: value;}
查看更多
临风纵饮
5楼-- · 2018-12-31 01:58

Is it possible to have more than one student in a class having same Roll/Id no? In HTMLid attribute is like so. You may use same class for them. e.g:

<div class="a b c"></div>
<div class="a b c d"></div>

And so on.

查看更多
浪荡孟婆
6楼-- · 2018-12-31 01:59

And for what it's worth, on Chrome 26.0.1410.65, Firefox 19.0.2, and Safari 6.0.3 at least, if you have multiple elements with the same ID, jquery selectors (at least) will return the first element with that ID.

e.g.

<div id="one">first text for one</div>
<div id="one">second text for one</div>

and

alert($('#one').size());

See http://jsfiddle.net/RuysX/ for a test.

查看更多
泛滥B
7楼-- · 2018-12-31 01:59

I think you can't do it because Id is unique you have to use it for one element . You can use class for the purpose

查看更多
登录 后发表回答