Can an html element have multiple ids?

前端 未结 18 2346
天命终不由人
天命终不由人 2020-11-22 07:40

I understand that an id must be unique within an HTML/XHTML page.

My question is, for a given element, can I assign multiple ids to it?

相关标签:
18条回答
  • 2020-11-22 08:02

    ID's should be unique, so you should only use a particular ID once on a page. Classes may be used repeatedly.

    check https://www.w3schools.com/html/html_id.asp for more details.

    0 讨论(0)
  • 2020-11-22 08:04

    You can only have one ID per element, but you can indeed have more than one class. But don't have multiple class attributes, put multiple class values into one attribute.

    <div id="foo" class="bar baz bax">
    

    is perfectly legal.

    0 讨论(0)
  • 2020-11-22 08:05

    I know this is a year old but I was curious about this myself and I'm sure others will find their way here. The simple answer is no, as others have said before me. An element can't have more than one ID and an ID can't be used more than once in a page. Try it out and you'll see how well it doesn't work.

    In reponse to tvanfosson's answer regarding the use of the same ID in two different elements. As far as I'm aware an ID can only be used once in a page regardless of whether it's attached to a different tag.

    By definition, an element needing an ID should be unique but if you need two ID's then it's not really unique and needs a class instead.

    0 讨论(0)
  • 2020-11-22 08:08

    No.

    Having said that, there's nothing to stop you doing it. But you'll get inconsistent behaviour with the various browsers. Don't do it. 1 ID per element.

    If you want multiple assignations to an element use classes (separated by a space).

    0 讨论(0)
  • 2020-11-22 08:09

    No. Every DOM element, if it has an id, has a single, unique id. You could approximate it using something like:

    <div id='enclosing_id_123'><span id='enclosed_id_123'></span></div>
    

    and then use navigation to get what you really want.

    If you are just looking to apply styles, class names are better.

    0 讨论(0)
  • 2020-11-22 08:11

    classes are specially made for this, here is the code from which you can understand

    <html>
    <head>
        <style type="text/css">
         .personal{
                height:100px;
                width: 100px;   
    
            }
        .fam{
                border: 2px solid #ccc;
            }   
        .x{
                background-color:#ccc;
            }   
    
        </style>
    </head>
    <body>
    
        <div class="personal fam x"></div>
    
    </body> 
    </html>
    
    0 讨论(0)
提交回复
热议问题