[英]Simple Javascript code issue
I am trying to insert a new image to an existing element. 我正在尝试将新图像插入现有元素。 I have
我有
var backImg = createElement('img', { className : 'link', src : '/images/btn.png' });
var save_bt=document.getElementsByClassName('button');
save_bt.appendChild(backImg);
The above codes gave me error:
Object #<NodeList> has no method 'appendChild'
Can anyone help me about it? 有人可以帮我吗? No Jquery codes plz.
没有Jquery代码plz。 Thanks a lot!
非常感谢!
document.getElementsByClassName('button')
returns a NodeList
, not an element. document.getElementsByClassName('button')
返回一个NodeList
,而不是一个元素。 If you want to add backImg
to every element with the class .button
you would need to loop through that NodeList: 如果要将
backImg
添加到带有.button
类的每个元素中,则需要遍历该NodeList:
for(var i=0,c=save_bt.length; i<c; i++){
save_bt[i].appendChild(backImg);
}
If you are trying to target a single element, you probably want to use id
HTML attribute instead of class
, then: 如果您要定位单个元素,则可能要使用
id
HTML属性而不是class
,然后:
document.getElementById('button').appendChild(backImg);
Note that HTML ids must be unique within the document. 请注意,HTML ID在文档中必须唯一。
如果您要定位单个元素,则应使用“ id”:
document.getElementById('id_of_the_element').src = "new_img.png";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.