Javascript 通过Id获取多个元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5338716/
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
Get multiple elements by Id
提问by osnoz
I have a page with anchor tags throughout the body like this:
我有一个页面,整个页面都带有锚标记,如下所示:
<a id="test" name="Name 1"></a>
<a id="test" name="Name 2"></a>
<a id="test" name="Name 3"></a>
The ID is always the same but the name changes.
ID 始终相同,但名称会更改。
I need to populate a list of the names of these anchor tags, for example; Name 1, Name 2, Name 3. This is where I've got to so far:
例如,我需要填充这些锚标记的名称列表;姓名 1、姓名 2、姓名 3。到目前为止,这是我要到达的地方:
document.write(document.getElementById("readme").name);
This writes out the name of the first anchor tag. I'm in need of a way to get multiple elements by Id.
这会写出第一个锚标记的名称。我需要一种通过 Id 获取多个元素的方法。
Any help is greatly appreciated.
任何帮助是极大的赞赏。
回答by erickb
If you can change the markup, you might want to use class
instead.
如果您可以更改标记,则可能需要class
改用。
<!-- html -->
<a class="test" name="Name 1"></a>
<a class="test" name="Name 2"></a>
<a class="test" name="Name 3"></a>
// javascript
var elements = document.getElementsByClassName("test");
var names = '';
for(var i=0; i<elements.length; i++) {
names += elements[i].name;
}
document.write(names);
回答by Shaz
As oppose to what others might say, using the same Id for multiple elements will not stop the page from being loaded, but when trying to select an element by Id, the only element returned is the first element with the id specified. Not to mention using the same id is not even valid HTML.
与其他人可能说的相反,对多个元素使用相同的 Id 不会阻止页面加载,但是当尝试通过 Id 选择元素时,返回的唯一元素是指定了 id 的第一个元素。更不用说使用相同的 id 甚至不是有效的 HTML。
That being so, never use duplicate id attributes. If you are thinking you need to, then you are looking for classinstead. For example:
既然如此,永远不要使用重复的 id 属性。如果您认为需要,那么您正在寻找课程。例如:
<div id="div1" class="mydiv">Content here</div>
<div id="div2" class="mydiv">Content here</div>
<div id="div3" class="mydiv">Content here</div>
Notice how each given element has a different id, but the same class. As oppose to what you did above, this is legal HTML syntax. Any CSS styles you use for '.mydiv' (the dot means class) will correctly work for each individual element with the same class.
请注意每个给定元素如何具有不同的 id,但具有相同的类。与您上面所做的相反,这是合法的 HTML 语法。您用于“.mydiv”(点表示类)的任何 CSS 样式都将适用于具有相同类的每个单独元素。
With a little help from Snipplr, you may use this to get every element by specifiying a certain class name:
在 Snipplr 的帮助下,您可以使用它通过指定某个类名来获取每个元素:
function getAllByClass(classname, node) {
if (!document.getElementsByClassName) {
if (!node) {
node = document.body;
}
var a = [],
re = new RegExp('\b' + classname + '\b'),
els = node.getElementsByTagName("*");
for (var i = 0, j = els.length; i < j; i++) {
if (re.test(els[i].className)) {
a.push(els[i]);
}
}
} else {
return document.getElementsByClassName(classname);
}
return a;
}
The above script will return an Array, so make sure you adjust properly for that.
上面的脚本将返回一个数组,因此请确保为此进行适当调整。
回答by Daniel A. White
You can't have duplicate ids. Ids are supposed to be unique. You might want to use a specialized class instead.
您不能有重复的 ID。ID 应该是唯一的。您可能想改用专门的类。
回答by Alexander Goncharov
Today you can select elements with the same id attribute this way:
今天,您可以通过这种方式选择具有相同 id 属性的元素:
document.querySelectorAll('[id=test]');
Or this way with jQuery:
或者用jQuery这种方式:
$('[id=test]');
CSS selector #test { ... }
should work also for all elements with id = "test"
. Вut the only thing: document.querySelectorAll('#test')
(or $('#test')
) - will return only a first element with this id.
Is it good, or not - I can't tell . But sometimes it is difficult to follow unique id standart.
CSS 选择器#test { ... }
也适用于所有带有id = "test"
. 唯一的事情:(document.querySelectorAll('#test')
或$('#test')
) - 将仅返回具有此 ID 的第一个元素。好不好 - 我不知道。但有时很难遵循唯一标识标准。
For example you have the comment widget, with HTML-ids, and JS-code, working with these HTML-ids. Sooner or later you'll need to render this widget many times, to comment a different objects into a single page: and here the standart will broken (often there is no time or not allow - to rewrite built-in code).
例如,您有带有 HTML-id 和 JS 代码的评论小部件,使用这些 HTML-id。迟早你需要多次渲染这个小部件,将不同的对象评论到一个页面中:这里标准将被破坏(通常没有时间或不允许 - 重写内置代码)。
回答by John
Here is a function I came up with
这是我想出的一个函数
function getElementsById(elementID){
var elementCollection = new Array();
var allElements = document.getElementsByTagName("*");
for(i = 0; i < allElements.length; i++){
if(allElements[i].id == elementID)
elementCollection.push(allElements[i]);
}
return elementCollection;
}
Apparently there is a convention supported by prototype, and probably other major JavaScript libraries.
显然原型支持一个约定,可能还有其他主要的 JavaScript 库。
However, I have come to discover that dollar sign function has become the more-or-less de facto shortcut to document.getElementById(). Let's face it, we all use document.getElementById() a lot. Not only does it take time to type, but it adds bytes to your code as well.
但是,我发现美元符号函数或多或少已成为 document.getElementById() 的事实上的快捷方式。让我们面对现实吧,我们都经常使用 document.getElementById()。不仅键入需要时间,而且还会向代码中添加字节。
here is the function from prototype:
这是原型中的函数:
function $(element) {
if (arguments.length > 1) {
for (var i = 0, elements = [], length = arguments.length; i < length; i++)
elements.push($(arguments[i]));
return elements;
}
if (Object.isString(element))
element = document.getElementById(element);
return Element.extend(element);
}
回答by akolade tinubu
You should use querySelectorAll, this writes every occurrence in an array and it allows you to use forEach to get individual element.
您应该使用 querySelectorAll,这会将每个出现的事件写入一个数组,并允许您使用 forEach 来获取单个元素。
document.querySelectorAll('[id=test]').forEach(element=>
document.write(element);
});
回答by sypl
If you're not religious about keeping your HTML valid then I can see use cases where having the same ID on multiple elements may be useful.
如果您不热衷于保持 HTML 有效,那么我可以看到在多个元素上使用相同 ID 可能有用的用例。
One example is testing. Often we identify elements to test against by finding all elements with a particular class. However, if we find ourselves adding classes purely for testing purposes, then I would contend that that's wrong. Classes are for styling, not identification.
一个例子是测试。通常,我们通过查找具有特定类的所有元素来确定要测试的元素。但是,如果我们发现自己添加类纯粹是为了测试目的,那么我认为这是错误的。类用于样式,而不是识别。
If IDs are for identification, why mustit be that only one element can have a particular identifier? Particularly in today's frontend world, with reusable components, if we don't want to use classes for identification, then we need to use IDs. But, if we use multiples of a component, we'll have multiple elements with the same ID.
如果 ID 用于标识,为什么必须只有一个元素可以具有特定的标识符?特别是在当今的前端世界,有了可重用的组件,如果我们不想使用类进行标识,那么我们需要使用 ID。但是,如果我们使用多个组件,我们将有多个具有相同 ID 的元素。
I'm saying that's OK. If that's anathema to you, that's fine, I understand your view. Let's agree to disagree and move on.
我是说没关系。如果这对你来说是一种诅咒,那很好,我理解你的观点。让我们同意不同意并继续前进。
If you want a solution that actually finds all IDs of the same name though, then it's this:
如果您想要一个实际找到所有同名 ID 的解决方案,那么就是这样:
function getElementsById(id) {
const elementsWithId = []
const allElements = document.getElementsByTagName('*')
for(let key in allElements) {
if(allElements.hasOwnProperty(key)) {
const element = allElements[key]
if(element.id === id) {
elementsWithId.push(element)
}
}
}
return elementsWithId
}
EDIT, ES6 FTW:
编辑,ES6 FTW:
function getElementsById(id) {
return [...document.getElementsByTagName('*')].filter(element => element.id === id)
}
回答by CloudyMarble
More than one Element with the same ID is not allowed, getElementById Returns the Element whose ID is given by elementId. If no such element exists, returns null. Behavior is not defined if more than one element has this ID.
不允许有多个具有相同 ID 的 Element, getElementById 返回 ID 由 elementId 给出的 Element。如果不存在这样的元素,则返回 null。如果多个元素具有此 ID,则行为未定义。
回答by Felix Jacob Borlongan
You can get the multiple element by id by identifying what element it is. For example
您可以通过标识它是什么元素来通过 id 获取多个元素。例如
<div id='id'></div>
<div id='id'></div>
<div id='id'></div>
I assume if you are using jQuery you can select all them all by
我假设如果您使用的是 jQuery,您可以通过
$("div#id")
$("div#id")
. This will get you array of elements you loop them based on your logic.
. 这将为您提供根据您的逻辑循环它们的元素数组。
回答by Yamid Ospina
With querySelectorAllyou can select the elements you want without the same id using css selector:
使用querySelectorAll,您可以使用 css 选择器在没有相同 id 的情况下选择您想要的元素:
var elems = document.querySelectorAll("#id1, #id1, #id3");