GetElementByID - Multiple IDs

Maurice Tempelsman picture Maurice Tempelsman · Jan 18, 2013 · Viewed 187.6k times · Source
doStuff(document.getElementById("myCircle1" "myCircle2" "myCircle3" "myCircle4"));

This doesn't work, so do I need a comma or semi-colon to make this work?

Answer

jfriend00 picture jfriend00 · Jan 18, 2013

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:

  1. You could implement your own function that takes multiple ids and returns multiple elements.
  2. You could use document.querySelectorAll() that allows you to specify multiple ids in a CSS selector string .
  3. 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"));