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.
js 對新手最不友好的地方在於沒有在可能出現與預期不符的行爲時報錯(貌似只有靜態語言能做到這一點哎)。
當然這樣的特性對入門之後是很友好的。。。
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsB...
HTMLCollection 是一個 array-like object 而不是 array,也不是 element,所以既沒有 array 的方法也沒有 element 的方法、屬性
因此我們從 Array 原型獲取所需的方法並調用。
當然你可以修改 HTMLCollection 原型實現快捷方式:
也可以採用現成的封裝比如 jQuery。
楼主获取的是一个集合,而不是单个img元素。可以根据索引获取到单个元素后修改对应属性
别用原生DOM API去搞了,换JQuery上吧:
多简洁
参考:JQuery教程 - w3cschool
公子正解
document.getElementsByClassName("classname") 返回的是一个对象数组(注意这里是Elements),
所以document.getElementsByClassName("classname")[0] 数组的第一个才是你要的DOM元素,
也可以用document.querySelector('.classname').src = url
建议你用jQuery吧,直接用JavaScript有些蛋疼,而且你还得考虑浏览器的兼容性