Can an html element have multiple ids?

2018-12-31 14:22发布

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?

<div id="nested_element_123 task_123"></div>

I realize I have an easy solution with simply using a class. I'm just curious about using ids in this manner.

17条回答
泪湿衣
2楼-- · 2018-12-31 14:57

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>
查看更多
若你有天会懂
3楼-- · 2018-12-31 14:59

My understanding has always been:

  • ID's are single use and are only applied to one element...

    • Each is attributed as a Unique Identifier to (only) one single element.
  • Classes can be used more than once...

    • They can therefore be applied to more than one element, and similarly yet different, there can be more than one class (i.e. multiple classes) per element.
查看更多
临风纵饮
4楼-- · 2018-12-31 14:59

Nay.

https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute

The value must not contain any space characters.

id="a b" <-- find the space character in that VaLuE.

That said, you can style multiple IDs. But if you're following spec, the answer is no.

查看更多
旧人旧事旧时光
5楼-- · 2018-12-31 15:00

No. While the definition from w3c for HTML 4 doesn't seem to explicitly cover your question, the definition of the name and id attribute says no spaces in the identifier:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

查看更多
只靠听说
6楼-- · 2018-12-31 15:02
Any ID assigned to a div element is unique.
However, you can assign multiple IDs "under", and not "to" a div element.
In that case, you have to represent those IDs as <span></span> IDs.

Say, you want two links in the same HTML page to point to the same div element in  the page.

The two different links
<p><a href="#exponentialEquationsCalculator">Exponential Equations</a></p>         

<p><a href="#logarithmicExpressionsCalculator"><Logarithmic Expressions</a></p>

Point to the same section of the page. 
<!-- Exponential / Logarithmic Equations Calculator -->
<div class="w3-container w3-card white w3-margin-bottom">      
   <span id="exponentialEquationsCalculator"></span>
   <span id="logarithmicEquationsCalculator"></span>
</div>
查看更多
大哥的爱人
7楼-- · 2018-12-31 15:03

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.

查看更多
登录 后发表回答