为什么我写
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/41008165/