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 15:05

I'd like to say technically yes, since really what gets rendered is technically always browser dependent. Most browsers try to keep to the specifications as best they can and as far as I know there is nothing in the css specifications against it. I'm only going to vouch for the actual html,css,javascript code that gets sent to the browser before any other interpretter steps in.

However I also say no since every browser I typically test on doesn't actually let you. If you need to see for yourself save the following as a .html file and open it up in the major browsers. In all browsers I tested on the javascript function will not match to an element. However, remove either "hunkojunk" from the id tag and all works fine. Sample Code

<html>
<head>
</head>
<body>
    <p id="hunkojunk1 hunkojunk2"></p>

<script type="text/javascript">
    document.getElementById('hunkojunk2').innerHTML = "JUNK JUNK JUNK JUNK JUNK JUNK";
</script>
</body>
</html>
查看更多
深知你不懂我心
3楼-- · 2018-12-31 15:07

No, you should use nested DIVs if you want to head down that path. Besides, even if you could, imagine the confusion it would cause when you run document.getElementByID(). What ID is it going to grab if there are multiple ones?

On a slightly related topic, you can add multiple classes to a DIV. See Eric Myers discussion at,

http://meyerweb.com/eric/articles/webrev/199802a.html

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

That's interesting, but as far as I know the answer is a firm no. I don't see why you need a nested ID, since you'll usually cross it with another element that has the same nested ID. If you don't there's no point, if you do there's still very little point.

查看更多
只若初见
5楼-- · 2018-12-31 15:09

No you cannot have multiple ids for a single tag, but I have seen a tag with a name attribute and an id attribute which are treated the same by some applications.

查看更多
人间绝色
6楼-- · 2018-12-31 15:09

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).

查看更多
登录 后发表回答