GetElementByID - Multiple IDs
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:
- 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.
Examples of each option:
doStuff(document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4"));
or:
// put a common class on each objectdoStuff(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"));
This will not work, getElementById
will query only one element by time.
You can use document.querySelectorAll("#myCircle1, #myCircle2")
for querying more then one element.
ES6 or newer
With the new version of the JavaScript, you can also convert the results into an array to easily transverse it.
Example:
const elementsList = document.querySelectorAll("#myCircle1, #myCircle2");const elementsArray = [...elementsList];// Now you can use cool array prototypeselementsArray.forEach(element => { console.log(element);});
How to query a list of IDs in ES6
Another easy way if you have an array of IDs is to use the language to build your query, example:
const ids = ['myCircle1', 'myCircle2', 'myCircle3'];const elements = document.querySelectorAll(ids.map(id => `#${id}`).join(', '));
No, it won't work.
document.getElementById()
method accepts only one argument.
However, you may always set classes to the elements and use getElementsByClassName()
instead. Another option for modern browsers is to use querySelectorAll()
method:
document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4");