The problem you're having is that getElementsById()
doesn't exist (unless you've defined it elsewhere). What you should be using is getElementById()
, albeit twice (as getElementById()
, as its name implies, returns only one element, even if there are multiple elements with that same id
, which is invalid mark-up, so please don't do that), and then pushing the returned elements into an array:
var products = [];
products.push(document.getElementById("id1"));
products.push(document.getElementById("id2"));
You could, of course, create your own function to return multiple elements based on their id
:
function getElementsById(ids) {
if (!ids) {
return false;
}
else {
var elems = [];
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i])) {
elems.push(document.getElementById(ids[i]));
}
}
return elems;
}
}
console.log(getElementsById(['id1','id3']));
JS Fiddle demo.
Bear in mind, though, that this returns a regular array, not a nodeList
(as would be returned, for example, by getElementsByClassName()
). And the returned array, even if it's only a single element, would have to be iterated over in the same way as any other array.
References: