Javascript GetElementByID - 多个 ID
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14408891/
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
GetElementByID - Multiple IDs
提问by Maurice Tempelsman
doStuff(document.getElementById("myCircle1" "myCircle2" "myCircle3" "myCircle4"));
This doesn't work, so do I need a comma or semi-colon to make this work?
这行不通,所以我需要逗号或分号来完成这项工作吗?
回答by jfriend00
document.getElementById()only supports one name at a time and only returns a single node not an array of nodes. You have several different options:
document.getElementById()一次只支持一个名称,并且只返回一个节点而不是节点数组。您有几种不同的选择:
- You could implement your own function that takes multiple ids and returns multiple elements.
- You could use
document.querySelectorAll()that allows you to specify multiple ids in a CSS selector string . - You could put a common class names on all those nodes and use
document.getElementsByClassName()with a single class name.
- 您可以实现自己的函数,该函数接受多个 id 并返回多个元素。
- 您可以使用
document.querySelectorAll()它允许您在 CSS 选择器字符串中指定多个 id。 - 您可以在所有这些节点上放置一个通用类名,并
document.getElementsByClassName()与单个类名一起使用。
Examples of each option:
每个选项的示例:
doStuff(document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4"));
or:
或者:
// put a common class on each object
doStuff(document.getElementsByClassName("circles"));
or:
或者:
function getElementsById(ids) {
var idList = ids.split(" ");
var results = [], item;
for (var i = 0; i < idList.length; i++) {
item = document.getElementById(idList[i]);
if (item) {
results.push(item);
}
}
return(results);
}
doStuff(getElementsById("myCircle1 myCircle2 myCircle3 myCircle4"));
回答by Gabriel Gartz
This will not work, getElementByIdwill query only one element by time.
这不起作用,getElementById将按时间仅查询一个元素。
You can use document.querySelectorAll("#myCircle1, #myCircle2")for querying more then one element.
您可以document.querySelectorAll("#myCircle1, #myCircle2")用于查询多个元素。
ES6 or newer
ES6 或更新版本
With the new version of the JavaScript, you can also convert the results into an array to easily transverse it.
使用新版本的 JavaScript,您还可以将结果转换为数组以轻松对其进行遍历。
Example:
例子:
const elementsList = document.querySelectorAll("#myCircle1, #myCircle2");
const elementsArray = [...elementsList];
// Now you can use cool array prototypes
elementsArray.forEach(element => {
console.log(element);
});
How to query a list of IDs in ES6
如何在 ES6 中查询 ID 列表
Another easy way if you have an array of IDs is to use the language to build your query, example:
如果您有一组 ID,另一种简单的方法是使用该语言来构建您的查询,例如:
const ids = ['myCircle1', 'myCircle2', 'myCircle3'];
const elements = document.querySelectorAll(ids.map(id => `#${id}`).join(', '));
回答by VisioN
No, it won't work.
不,这行不通。
document.getElementById()method accepts only one argument.
document.getElementById()方法只接受一个参数。
However, you may always set classes to the elements and use getElementsByClassName()instead. Another option for modern browsers is to use querySelectorAll()method:
但是,您可以始终为元素设置类并getElementsByClassName()改为使用。现代浏览器的另一个选择是使用querySelectorAll()方法:
document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4");
回答by Oriol
I suggest using ES5 array methods:
我建议使用 ES5 数组方法:
["myCircle1","myCircle2","myCircle3","myCircle4"] // Array of IDs
.map(document.getElementById, document) // Array of elements
.forEach(doStuff);
Then doStuffwill be called once for each element, and will receive 3 arguments: the element, the index of the element inside the array of elements, and the array of elements.
然后doStuff将为每个元素调用一次,并将接收 3 个参数:元素、元素数组内元素的索引和元素数组。
回答by Vulgo Alias
Dunno if something like this works in js, in PHP and Python which i use quite often it is possible. Maybe just use for loop like:
不知道如果这样的东西在 js、PHP 和 Python 中工作,我经常使用它是可能的。也许只是使用 for 循环,如:
function doStuff(){
for(i=1; i<=4; i++){
var i = document.getElementById("myCiricle"+i);
}
}
回答by Dan Zuzevich
Vulgo has the right idea on this thread. I believe his solution is the easiest of the bunch, although his answer could have been a little more in-depth. Here is something that worked for me. I have provided an example.
Vulgo 在这个线程上有正确的想法。我相信他的解决方案是最简单的,尽管他的回答可能更深入一些。这是对我有用的东西。我提供了一个例子。
<h1 id="hello1">Hello World</h1>
<h2 id="hello2">Random</h2>
<button id="click">Click To Hide</button>
<script>
document.getElementById('click').addEventListener('click', function(){
doStuff();
});
function doStuff() {
for(var i=1; i<=2; i++){
var el = document.getElementById("hello" + i);
el.style.display = 'none';
}
}
</script>
Obviously just change the integers in the for loop to account for however many elements you are targeting, which in this example was 2.
显然,只需更改 for 循环中的整数即可考虑您要定位的元素数量,在本例中为 2。
回答by EsterlingAccime Youtuber
The best way to do it, is to define a function, and pass it a parameter of the ID's name that you want to grab from the DOM, then every time you want to grab an ID and store it inside an array, then you can call the function
最好的方法是定义一个函数,并传递一个你想从 DOM 中获取的 ID 名称的参数,然后每次你想要获取一个 ID 并将其存储在一个数组中,然后你就可以调用函数
<p id="testing">Demo test!</p>
function grabbingId(element){
var storeId = document.getElementById(element);
return storeId;
}
grabbingId("testing").syle.color = "red";
回答by Samir Vukasinovic
You can use something like this whit array and for loop.
您可以使用类似这个 whit 数组和 for 循环的东西。
<p id='fisrt'>??????</p>
<p id='second'>??????</p>
<p id='third'>??????</p>
<p id='forth'>??????</p>
<p id='fifth'>??????</p>
<button id="change" onclick="changeColor()">color red</button>
<script>
var ids = ['fisrt','second','third','forth','fifth'];
function changeColor() {
for (var i = 0; i < ids.length; i++) {
document.getElementById(ids[i]).style.color='red';
}
}
</script>
回答by sachleen
getElementByIDis exactly that - get an element by id.
getElementByID就是这样 - 通过 id 获取元素。
Maybe you want to give those elements a circleclass and getElementsByClassName
也许你想给这些元素一个circle类getElementsByClassName
回答by MuhammadHani
document.getElementById()only takes one argument. You can give them a class name and use getElementsByClassName().
document.getElementById()只需要一个参数。你可以给他们一个类名并使用getElementsByClassName().

