具有相同 ID 的多个元素的 JavaScript 和 getElementById

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3607291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 05:24:54  来源:igfitidea点击:

JavaScript and getElementById for multiple elements with the same ID

javascript

提问by Rajan P

How can I get a collection of elements by specifying their idattribute? I want to get the name of all the tags which have the same idin the html.

如何通过指定元素的id属性来获取元素的集合?我想获取id在 html 中具有相同标签的所有标签的名称。

I want to use ONLY getElementById()to get an array of elements. How can I do this?

我想使用 ONLYgetElementById()来获取元素数组。我怎样才能做到这一点?

回答by Oded

The HTML specrequired the IDattribute to be unique in a page:

HTML规范所要求的ID属性是在一个页面独特之处:

This attribute assigns a name to an element. This name must be unique in a document.

此属性为元素分配名称。此名称在文档中必须是唯一的。

If you have several elements with the same ID, your HTML is not valid.

如果您有多个具有相同 ID 的元素,则您的 HTML 无效。

So, getElementById()should only ever return one element. You can't make it return multiple elements.

所以,getElementById()应该只返回一个元素。你不能让它返回多个元素。

There are a couple of related functions that will return an array of elements - getElementsByName, or getElementsByClassNamethat may be more suited to your requirements, though getElementsByClassNameis new to HTML 5, which is still in draft.

有几个相关的函数将返回一个元素数组 - getElementsByName,或者getElementsByClassName可能更适合您的要求,尽管getElementsByClassName它是 HTML 5 的新功能,它仍处于草案中。

回答by Brad Bamford

I know this is an old question and that an HTML page with multiple IDs is invalid. However, I ran into this issues while needing to scrape and reformat someone else's API's HTML documentation that contained duplicate IDs (invalid HTML).

我知道这是一个老问题,并且具有多个 ID 的 HTML 页面无效。但是,我在需要抓取和重新格式化包含重复 ID(无效 HTML)的其他人的 API 的 HTML 文档时遇到了这个问题。

So for anyone else, here is the code I used to work around the issue using querySelectorAll:

所以对于其他人,这是我用来解决这个问题的代码querySelectorAll

var elms = document.querySelectorAll("[id='duplicateID']");

for(var i = 0; i < elms.length; i++) 
  elms[i].style.display='none'; // <-- whatever you need to do here.

回答by Paul Butcher

Why you would want to do this is beyond me, since id is supposed to be unique in a document. However, browsers tend to be quite lax on this, so if you really must use getElementById for this purpose, you can do it like this:

为什么要这样做超出了我的理解,因为 id 在文档中应该是唯一的。然而,浏览器在这方面往往很松懈,所以如果你真的必须为此使用 getElementById,你可以这样做:

function whywouldyoudothis() {
    var n = document.getElementById("non-unique-id");
    var a = [];
    var i;
    while(n) {
        a.push(n);
        n.id = "a-different-id";
        n = document.getElementById("non-unique-id");
    }

    for(i = 0;i < a.length; ++i) {
        a[i].id = "non-unique-id";      
    }
    return a;
}

However, this is silly, and I wouldn't trust this to work on all browsers forever. Although the HTML DOM spec defines id as readwrite, a validating browser will complain if faced with more than one element with the same id.

但是,这很愚蠢,我不相信它会永远在所有浏览器上运行。尽管 HTML DOM 规范将 id 定义为 readwrite,但如果遇到多个具有相同 id 的元素,验证浏览器会抱怨。

EDIT: Given a valid document, the same effect could be achieved thus:

编辑:给定一个有效的文件,同样的效果可以这样实现:

function getElementsById(id) {
  return [document.getElementById(id)];
}

回答by cprcrack

document.querySelectorAll("#yourId");returns all elements whose id is yourId

document.querySelectorAll("#yourId");返回 id 为的所有元素 yourId

回答by Delan Azabani

It is illegal to have multiple elements with the same id. The idis used as an individual identifier. For groups of elements, use class, and getElementsByClassNameinstead.

多个元素具有相同的id. 将id被用作一个单独的标识符。对于元素组,请使用class, 和getElementsByClassName代替。

回答by remi bourgarel

The id is supposed to be unique, use the attribute "name" and "getelementsbyname" instead, and you'll have your array.

id 应该是唯一的,使用属性“name”和“getelementsbyname”代替,你就会有你的数组。

回答by Christian L?irbag

Class is more than enough for refering anything you want, because it can have a naming with one of morewords:

Class 足以引用您想要的任何内容,因为它可以使用多个单词之一命名:

<input class="special use">
<input class="normal use">
<input class="no use">
<input class="special treatment">
<input class="normal treatment">
<input class="no special treatment">
<input class="use treatment">

that's the way you can apply different styles with css (and Bootstrap is the best example of it) and of course you may call

这就是你可以用 css 应用不同样式的方式(Bootstrap 是最好的例子),当然你可以调用

document.getElementsByClassName("special");
document.getElementsByClassName("use");
document.getElementsByClassName("treatment");
document.getElementsByClassName("no");
document.getElementsByClassName("normal");

and so on for any grouping you need.

等等任何你需要的分组。

Now, in the very last case you really want to group elements by id. You may use and refer to elements using a numerically similar, but not equal id:

现在,在最后一种情况下,您确实希望按 id 对元素进行分组。您可以使用数字上相似但不相等的 id 来使用和引用元素:

<input id=1>
<input id="+1">
<input id="-1">
<input id="1 ">
<input id=" 1">
<input id="0x1">
<input id="1.">
<input id="1.0">
<input id="01.0">
<input id="001">

That way you can, knowing the numeric id, access and get an element by just adding extra non-invalidating numeric characters and calling a function to get (by parsing and so on) the original index from its legal string identifying value. It is useful for when you:

这样,您可以在知道数字 id 的情况下,通过添加额外的非无效数字字符并调用函数从其合法字符串标识值中获取(通过解析等)原始索引来访问和获取元素。当您:

  • Have several rows with similar elements and want to handle its events coherently. No matter if you delete one or almost all of them. Since numeric reference is still present, you can then reuse them and reassign its deleted format.

  • Run out of class, name and tagname identifiers.

  • 有几行具有相似元素并希望连贯地处理其事件。无论您是删除其中一个还是几乎所有。由于数字引用仍然存在,因此您可以重复使用它们并重新分配其已删除的格式。

  • 用完类、名称和标记名标识符。

Although you can use spaces and other common signs even when it's a not a requirement strictly validated in browsers, it's not recommended to use them, specially if you are going to send that data in other formats like JSON. You may even handle such things with PHP, but this is a bad practice tending to filthy programming practices.

尽管您可以使用空格和其他常见符号,即使它不是在浏览器中严格验证的要求,但不建议使用它们,特别是如果您打算以其他格式(如 JSON)发送该数据。您甚至可以使用 PHP 处理此类事情,但这是一种倾向于肮脏的编程实践的不良做法。

回答by Ismael Covarrubias

As others have stated, you shouldn't have the same ID more than once in your HTML, however... elements with an ID are attached to the documentobject and to windowon Internet Explorer. Refer to:

正如其他人所说,您的 HTML 中不应多次使用相同的 ID,但是...具有 ID 的元素附加到文档对象和Internet Explorer上的窗口。参考:

Do DOM tree elements with ids become global variables?

带有 id 的 DOM 树元素会成为全局变量吗?

If more than one element with the same ID exists in your HTML, this property is attached as an array. I'm sorry, but I don't know where to look if this is the standard behavior or at least you get the same behavior between browsers, which I doubt.

如果 HTML 中存在多个具有相同 ID 的元素,则此属性将作为数组附加。我很抱歉,但我不知道在哪里查看这是否是标准行为,或者至少您在浏览器之间获得相同的行为,我对此表示怀疑。

回答by yasin ullah

you can use document.document.querySelectorAll("#divId")

你可以使用 document.document.querySelectorAll("#divId")

回答by Moin Zaman

You shouldn't do that and even if it's possible it's not reliable and prone to cause issues.

您不应该这样做,即使可能这样做也不可靠并且容易引起问题。

Reason being that an ID is unique on the page. i.e. you cannot have more than 1 element on the page with the same ID.

原因是 ID 在页面上是唯一的。即页面上不能有超过 1 个具有相同 ID 的元素。