Getelementbyid - Multiple Ids
DoStuff(document. getElementById("myCircle1" "Mycircle2" "Mycircle3" "Mycircle4")); This Doesn't Work, So Do I Need a Comma or Semi-Colon to Make This Work? 1...
doStuff(document.getElementById("myCircle1" "myCircle2" "myCircle3" "myCircle4"));
This doesn't work, so do I need a comma or semi-colon to make this work?
15 Answers
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 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"));
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.
Must Read
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 prototypes
elementsArray.forEach(element => {
console.log(element);
});