As many have pointed out document.getElementsByClassName("myclass");
returns a NodeList and not an array. So you can not exploit native array methods like indexOf
or forEach
. From the docs:
NodeList are used very much like arrays and it would be tempting to use Array.prototype methods on them, however they don't have those methods.JavaScript has an inheritance mechanism based on prototypes for both built–in objects (like Arrays) and host objects (like NodeLists). Array instances inherit array methods (such as forEach or map) because their prototype chain looks like the following:
myArray --> Array.prototype --> Object.prototype --> null (The prototype chain of an object can be obtained by calling Object.getPrototypeOf several times.)
That said, you would basically want to convert the NodeList to an array. You could do something like:
var turnObjToArray = function(obj) {
return [].map.call(obj, function(element) {
return element;
})
};
var a=document.getElementById("a");
var b=document.getElementById("b");
var pe=document.getElementsByClassName("o");
var listBox = turnObjToArray(pe);
console.log(listBox);
alert(listBox.indexOf(a)); //Normal array methods can be used here.
DEMO
Hope it gets you started in the right direction.