js 對新手最不友好的地方在於沒有在可能出現與預期不符的行爲時報錯(貌似只有靜態語言能做到這一點哎)。
當然這樣的特性對入門之後是很友好的。。。
Returns an array-like object of all child elements which have all of
the given class names. When called on the document object, the
complete document is searched, including the root node. You may also
call getElementsByClassName() on any element; it will return only
elements which are descendants of the specified root element with the
given class names.
var elements = document.getElementsByClassName(names);
elements is a live HTMLCollection of found elements.
HTMLCollection 是一個 array-like object 而不是 array,也不是 element,所以既沒有 array 的方法也沒有 element 的方法、屬性
因此我們從 Array 原型獲取所需的方法並調用。
Array.prototype.forEach.call(document.getElementsByClassName("classname"), function(x){ x.attribute = newValue });
當然你可以修改 HTMLCollection 原型實現快捷方式:
HTMLCollection.prototype.setAttr = function(name, value) {
Array.prototype.forEach.call(this, function(x){ x[name] = value; });
};
document.getElementsByClassName("classname").setAttr('attribute', newValue);
也可以採用現成的封裝比如 jQuery。