doStuff(document.getElementById("myCircle1" "myCircle2" "myCircle3" "myCircle4"));
This doesn't work, so do I need a comma or semi-colon to make this work?
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.querySelectorAll()
that allows you to specify multiple ids in a CSS selector string .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.
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); });
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(', '));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With