如果多个不同的HTML元素是不同的元素,它们可以具有相同的ID吗?

时间:2011-04-10 13:14:02

标签: html dom

这样的场景是否有效?:

div#foo
span#foo
a#foo

18 个答案:

答案 0 :(得分:161)

没有

元素ID在整个文档中应该是唯一的。

答案 1 :(得分:75)

我认为某些东西应该是唯一的还是必须是唯一的(即由网络浏览器强制执行)之间存在差异。

ID应该是唯一的吗? YES。

必须ID是唯一的吗?不,至少IE和FireFox允许多个元素具有相同的ID。

答案 2 :(得分:39)

多个元素可以具有相同的ID吗?

是 - 无论它们是否是相同的标签,即使多个元素具有相同的ID,浏览器也会呈现页面。

是否有效HTML?

没有。从HTML 5.1 spec开始,这仍然是正确的。但是,该规范还说getElementById must return the first element with the given ID,在无效文档的情况下,行为未定义。

此类无效HTML的后果是什么?

大多数(如果不是全部)浏览器在调用getElementById时已选择并仍然执行选择具有给定ID的第一个元素。大多数通过ID查找元素的库都会继承此行为。大多数(如果不是全部)浏览器还将id-selectors(例如#myid)分配的样式应用于具有指定ID的所有元素。如果这是您期望和打算的,那么就不会产生意想不到的后果。如果您期望/打算其他东西(例如,对于具有该ID的所有元素都要返回,或者样式仅适用于一个元素)那么您的期望将无法满足,任何依赖于这些期望的功能都将失败。

当多个元素具有相同的ID时,某些javascript库 do 会产生不满足的期望(请参阅wootscootinboogie's comment关于d3.js)

<强>结论

如果您的代码在当前环境中按预期工作,并且这些ID以可预测/可维护的方式使用,那么只有两个实际原因需要考虑不这样做:

  1. 为避免您出错的可能性,当多个元素具有相同ID时,实际使用的其中一个库出现故障。
  2. 为了保持您的网站/应用程序与图书馆或服务(或开发人员!)的向前兼容性,这些图书馆或服务(或开发人员!)在多个元素具有相同ID时出现故障,您将来可能会遇到此问题。
  3. 权力是你的!

答案 3 :(得分:23)

即使元素属于不同类型,也会导致一些严重的问题......

假设您有3个具有相同ID的按钮:

<button id="myid" data-mydata="this is button 1">button 1</button>
<button id="myid" data-mydata="this is button 2">button 2</button>
<button id="myid" data-mydata="this is button 3">button 3</button>

现在您设置了一些jQuery代码,以便在点击myid按钮时执行操作:

$(document).ready(function ()
{
    $("#myid").click(function ()
    {
        var buttonData = $(this).data("mydata");

        // Call interesting function...
        interestingFunction();

        $('form').trigger('submit');
    });
});

你会期待什么?单击每个按钮将使用jQuery执行单击事件处理程序设置。不幸的是,它不会发生。只有 1st 按钮才会调用点击处理程序。点击时其他2个什么都不做。就好像它们根本不是按钮一样!

因此,请始终为IDs元素分配不同的HTML元素。这将让你对抗奇怪的事情。 :)

<button id="button1" class="mybtn" data-mydata="this is button 1">button 1</button>
<button id="button2" class="mybtn" data-mydata="this is button 2">button 2</button>
<button id="button3" class="mybtn" data-mydata="this is button 3">button 3</button>

现在,如果您希望在单击任何按钮时运行click事件处理程序,那么如果您更改jQuery代码中的选择器以使用应用于它们的CSS类,它将完美地工作:

$(document).ready(function ()
{
    $(".mybtn").click(function ()
    {
        var buttonData = $(this).data("mydata");

        // Call interesting function...
        interstingFunction();

        $('form').trigger('submit');
    });
});

答案 4 :(得分:22)

没有。具有相同id的两个元素无效。 ID是唯一的,如果您希望执行类似的操作,请使用类。不要忘记,通过使用空格作为分隔符,元素可以有多个类:

<div class="myclass sexy"></div>

答案 5 :(得分:11)

HTML的官方规范指出id标签必须是唯一的 AND 官方规范还指出如果渲染可以完成,它必须(即没有“错误”之类的东西HTML,只有“无效”的HTML)。 因此,以下是id标记在实践中的实际工作方式。它们都无效,但仍有效:

此:

<div id="unique">One</div>
<div id="unique">Two</div>

在所有浏览器中呈现正常。但是,document.getElementById只返回一个对象,而不是一个数组;你只能通过id标签选择第一个div。如果您要使用JavaScript更改第一个div的ID,则可以使用document.getElementById访问第二个ID(在Chrome,FireFox和IE11上测试)。您仍然可以使用其他选择方法选择div,并且将正确返回它的id属性。

请注意上述问题在呈现SVG图像的网站中打开了一个潜在的安全漏洞,因为允许SVG包含DOM元素,并且还包含ID标记(允许脚本DOM通过上传的图像重定向) )。只要SVG在它替换的元素之前位于DOM中,图像就会接收所有用于其他元素的JavaScript事件。

据我所知,目前这个问题并没有被任何人所关注,但它确实存在。

此:

<div id="unique" id="unique-also">One</div>

在所有浏览器中也可以正常呈现。但是,如果您尝试使用document.getElementById('unique-also'),则只使用您使用此方式定义的第一个 ID。在上面的示例中,您将返回 null (在Chrome,FireFox和IE11上测试)。

此:

<div id="unique unique-two">Two</div>

同样在所有浏览器中渲染都很好,但是,与可以用空格分隔的类标签不同,id标签允许空格,所以上面元素的id实际上是“唯一唯一 - 两个”,并且要求dom为隔离的“unique”或“unique-two”返回 null ,除非在DOM的其他地方另有定义(在Chrome,FireFox和IE11上测试)。

答案 6 :(得分:5)

SLaks答案是正确的,但作为附录注释,x / html规范指定所有ID在(单个)html文档中必须是唯一的。虽然它并不完全是op所要求的,但可能存在有效的实例,其中相同的id连接到多个页面的不同实体。

示例:

(服务于现代浏览器)文章#main-content {单向风格}  (服务于遗产)div #main-content {另一种方式}

可能是反模式。离开这里作为魔鬼的支持者。

答案 7 :(得分:3)

至于它的价值,至少在Chrome 26.0.1410.65,Firefox 19.0.2和Safari 6.0.3上,如果你有多个具有相同ID的元素,jquery选择器(至少)将返回第一个元素那个ID。

e.g。

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

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

请参阅http://jsfiddle.net/RuysX/进行测试。

答案 8 :(得分:3)

好吧,使用特定于HTML5的HTML validator at w3.org,ID必须是唯一的

考虑以下内容......

<!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>

验证者回复......

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>

...但是OP明确说明了 - 不同的元素类型怎么样。请考虑以下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>

......验证器的结果是......

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

结论:

在任何一种情况下(相同的元素类型或不同的元素类型),如果id被多次使用,则不被认为是有效的HTML5。

答案 9 :(得分:3)

是的。

我不知道所有这些答案是否已过时,只是打开youtube并检查html。尝试查看建议的视频,您将看到它们具有相同的ID和重复结构,如下所示:

<span id="video-title" class="style-scope ytd-compact-radio-renderer" title="Mix - LARA TACTICAL">

答案 10 :(得分:2)

务实的答案如何?

我们去youtube并运行此代码

Object.fromEntries(Object.entries([...document.querySelectorAll('[id]')].reduce((s, e) => { s[e.id] = (s[e.id] || 0) + 1; return s; }, {})).filter(([k,v]) => v > 1))

并查看所有重复的ID。

enter image description here

更改上面的代码以显示ID重复10次以上,这是它产生的列表

additional-metadata-line: 43
avatar: 46
avatar-link: 43
button: 120
buttons: 45
byline-container: 45
channel-name: 44
container: 51
content: 49
details: 43
dismissable: 46
dismissed: 46
dismissed-content: 43
hover-overlays: 45
img: 90
menu: 50
meta: 44
metadata: 44
metadata-line: 43
mouseover-overlay: 45
overlays: 45
repeat: 36
separator: 43
text: 49
text-container: 44
thumbnail: 46
tooltip: 80
top-level-buttons: 45
video-title: 43
video-title-link: 43

多次使用相同ID的其他网站包括Amazon.com,ebay.com,expedia.com,cnn.com

显然,id只是元素上的另一元数据。

getElementById已经过时了。不管选择器是什么,都可以对所有元素使用querySelectorAll或对第一个元素使用querySelector,因此,如果要使用ID为foo的所有元素,则

document.querySelectorAll('#foo')  // returns all elements with id="foo"

好像只希望第一个元素使用querySelector

document.querySelector('#foo')  // returns the first element with id="foo"
document.querySelector('.foo')  // returns the first element with class "foo"
document.querySelector('foo')   // returns the first <foo> element
document.querySelector('foo .foo #foo') // returns the first element with
                                        // id="foo" that has an ancestor
                                        // with class "foo" who has an
                                        // ancestor <foo> element.

我们可以看到,使用选择器可以找到具有相同id的不同元素。

function addClick(selector, add) {
  document.querySelector(selector).addEventListener('click', function() {
    const e = this.parentElement.querySelector('span');
    e.textContent = parseInt(e.textContent) + add;
  });
}
addClick('.e #foo', 1);
addClick('.f #foo', 10);
body { font-size: x-large; font-weight: bold; }
.a #foo { color: red; }
.b #foo { color: green; }
div:nth-child(3) #foo { color: blue; }
#foo { color: purple }
<div class="a"><span id="foo">a</span></div>
<div class="b"><span id="foo">b</span></div>
<div><span id="foo">c</span></div>
<span id="foo">d</span>
<div class="e"><button type="button" id="foo">+1</button>: <span>0</span></div>
<div class="f"><button type="button" id="foo">+10</button>: <span>0</span></div>

重要的是ID是唯一的

  • <a>标签可以引用<a href="#foo">中的ID。单击它会将文档跳转到带有id="foo"的第一个元素。同样,URL中的哈希标签实际上是相同的功能。

  • <label>标签具有for属性,该属性指定它们使用id标记的元素。单击标签单击/激活/给予焦点到相应的元素。标签只会影响具有匹配ID的第一个元素

label { user-select: none; }
<p>nested for checking</p>
<form>
  <div><input type="checkbox" id="foo"><label for="foo">foo</label></div>
</form>
<form>
  <div><input type="checkbox" id="foo"><label for="foo">foo (clicking here will check first checkbox)</label></div>
</form>

否则,id只是您工具箱中的另一个工具。

答案 11 :(得分:1)

我们可以使用类名代替ID。 html id应该是唯一的,但类不是。使用类名检索数据时,可以减少js文件中的代码行数。

$(document).ready(function ()
{
    $(".class_name").click(function ()
    {
        //code
    });
});

答案 12 :(得分:1)

可能有重复的 ID。我尝试从 javascript 添加 todoitem 并成功添加到 dom 中。这是 html 代码和 javscript 代码。 I have tried adding the todoitem from javascript and it added to the dom successfully. This is the html code.

This is the javascript code.

答案 13 :(得分:0)

是否可以在具有相同Roll / Id no的班级中拥有多个学生?在HTML id属性中是这样的。您可以为他们使用相同的课程。 e.g:

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

等等。

答案 14 :(得分:0)

不,ID必须是唯一的。您可以为此目的使用类

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

div.a {font: ...;}
/* or just: */
.a {prop: value;}

答案 15 :(得分:0)

我认为你不能这样做,因为Id是独一无二的,你必须将它用于一个元素。您可以将类用于此目的

答案 16 :(得分:0)

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

var ids = document.getElementById('one');

ids只包含第一个div元素。因此,即使有多个具有相同id的元素,文档对象也只返回第一个匹配。

答案 17 :(得分:0)

通常,最好不要在html页面中多次使用相同的ID。 即使这样,也可以在一个页面中多次使用相同的ID。 但是,当您使用ID作为URI / URL的一部分时,如下所示:

https://en.wikipedia.org/wiki/FIFA_World_Cup#2015_FIFA_corruption_case

并且如果ID('2015_FIFA_corruption_case')仅用于网页中的一个(跨度)元素:

<span class="mw-headline" id="2015_FIFA_corruption_case">2015 FIFA corruption case</span>

没有问题。相反,同一ID存在多个地方,浏览器会感到困惑。