前端 - JavaScript 无法修改 html 元素的属性是怎么回事?
巴扎黑
巴扎黑 2017-04-10 15:11:10
[JavaScript讨论组]

rt,检查了好久,也没能找到原因。。。
这些代码的目的是先获得新的url值,然后替换掉原来的image元素的src属性为新的url值,通过这个来达到变更图片的目的。。。
然而一直试都是没能改过来。。。
按理来说:
document.getElementsByClassName("classname").attribute = newValue;
不是可以修改类名为"classname"的元素的属性么?
求助,万分感谢!!!

巴扎黑
巴扎黑

全部回复(6)
迷茫
document.getElementsByClassName("classname")[0].src = url;
大家讲道理

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.

https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsB...

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。

PHP中文网

楼主获取的是一个集合,而不是单个img元素。可以根据索引获取到单个元素后修改对应属性

PHP中文网

别用原生DOM API去搞了,换JQuery上吧:

$('.avatar').attr('src', url_avatar);

多简洁

参考:JQuery教程 - w3cschool

天蓬老师

公子正解
document.getElementsByClassName("classname") 返回的是一个对象数组(注意这里是Elements),
所以document.getElementsByClassName("classname")[0] 数组的第一个才是你要的DOM元素,
也可以用document.querySelector('.classname').src = url

ringa_lee

建议你用jQuery吧,直接用JavaScript有些蛋疼,而且你还得考虑浏览器的兼容性

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号