Can multiple different HTML elements have the same ID if they're different elements?

后端 未结 16 1849
无人及你
无人及你 2020-11-21 05:30

Can multiple HTML elements have the same ID if they\'re of different element types? Is a scenario like this valid? Eg:

div#foo
span#foo
a#foo
16条回答
  •  执笔经年
    2020-11-21 06:02

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

    Consider the following...

     
    
        
            
            MyTitle 
        
        
            
    Barry
    was
    here

    the validator responds with ...

    Line 9, Column 14: Duplicate ID x.      
    was
    Warning Line 8, Column 14: The first occurrence of ID x was here.
    Barry
    Error Line 10, Column 14: Duplicate ID x.
    here
    Warning Line 8, Column 14: The first occurrence of ID x was here.
    Barry

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

     
    
        
            
            MyTitle 
        
        
            
    barry was here

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

    Line 9, Column 16: Duplicate ID x.          was here
    Warning Line 8, Column 14: The first occurrence of ID x was here.       
    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.

提交回复
热议问题