加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 资源网站 > 资源 > 正文

javascript – getElementByClass().setAttribute不起作用

发布时间:2020-12-14 22:59:03 所属栏目:资源 来源:网络整理
导读:为什么当我写作 document.getElementByClass('home1').setAttribute('style','background-image:url(img/red_menu.PNG);'); 它不起作用? 我有class =“home1”的元素 与document.getElementById(home1) 工作良好 谢谢 最佳答案 它是getElementsByClassName,

为什么当我写作

document.getElementByClass('home1').setAttribute('style','background-image:url(img/red_menu.PNG);');

它不起作用?
我有class =“home1”的元素

与document.getElementById(‘home1’)…
工作良好
谢谢

最佳答案
它是getElementsByClassName,而不是getElementByClass; details here.注意IE确实是not support this function(尚未).

getElementsByClassName返回匹配元素的NodeList(而不是单个元素),因此:

var list,index;
list = document.getElementsByClassName("home1");
for (index = 0; index < list.length; ++index) {
    list[index].setAttribute(/* ... */);
}

对于这种情况,您可能希望使用像jQuery,Prototype,Google Closure等库来为您分配各种浏览器差异.与自己处理这些差异相比,它们可以为您节省大量时间和麻烦.

例如,在jQuery中:

$(".home1").attr(/* ... */);

…将该属性(通过jQuery#attr)应用于具有“home1”类的每个元素.虽然在您的特定情况下,您可能需要jQuery#css.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读