getElementByClass()。setAttribute不起作用 [英] getElementByClass().setAttribute doesn't work
问题描述
为什么当我写的时候
document.getElementByClass('home1')。setAttribute('style','background-image :网址(IMG / red_menu.PNG);');
不起作用?
i包含元素 class =home1
与文档。 getElementById('home1')...
正常工作
谢谢
它是 getElementsByClassName
,而不是 getElementByClass
;这里详情。请注意,IE不支持不支持此功能 (还)。
getElementsByClassName
返回匹配元素的NodeList(而不是单个元素),所以:
var list,index;
list = document.getElementsByClassName(home1);
for(index = 0; index< list.length; ++ index){
list [index] .setAttribute(/ * ... * /);
$ / code>
对于这种情况,您可能需要使用类似 jQuery ,原型, Google Closure 等,为各种浏览器差异铺平了道路。例如,在jQuery中:
$(。home1)。attr(/ * ... * /);
...应用该属性(通过 jQuery#attr
)添加到类为home1的每个元素。虽然在你的特定情况下,你可能会希望 jQuery#css
代替。
why when i write
document.getElementByClass('home1').setAttribute('style', 'background-image:url(img/red_menu.PNG);');
it doesn't work?
i have the element with class="home1"
with document.getElementById('home1')...
works fine
thanks
It's getElementsByClassName
, not getElementByClass
; details here. Note that IE does not support this function (yet).
getElementsByClassName
returns a NodeList of matching elements (rather than a single element), so:
var list, index;
list = document.getElementsByClassName("home1");
for (index = 0; index < list.length; ++index) {
list[index].setAttribute(/* ... */);
}
For this sort of thing, you may want to use a library like jQuery, Prototype, Google Closure, etc., to pave over the various browser differences for you. They can save you a lot of time and trouble compared with dealing with those differences yourself.
For instance, in jQuery:
$(".home1").attr(/* ... */);
...applies that attribute (via jQuery#attr
) to every element with the class "home1". Although in your particular case, you'd probably want jQuery#css
instead.
这篇关于getElementByClass()。setAttribute不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!