为什么我写
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
相反。
关于javascript - getElementByClass().setAttribute 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2565909/