原生JavaScript通过name获取dom元素得到的是
HTMLCollection元素集合
要想循环遍历可以用forEach,但是在低于ie9的版本下不兼容
var list= document.getElementsByName("name");
for (var i = 0; i < list.length; i++) {
console.log(list[i].id); //second console output
}
数组的时候可以向Array.prototype加一个自定义方法forEach
如下:
if ( !Array.prototype.forEach ) {
Array.prototype.forEach = function forEach( callback, thisArg ) {
var T, k;
if ( this == null ) {
throw new TypeError( "this is null or not defined" );
}
var O = Object(this);
var len = O.length >>> 0;
if ( typeof callback !== "function" ) {
throw new TypeError( callback + " is not a function" );
}
if ( arguments.length > 1 ) {
T = thisArg;
}
k = 0;
while( k < len ) {
var kValue;
if ( k in O ) {
kValue = O[ k ];
callback.call( T, kValue, k, O );
}
k++;
}
};
}