Rouge
Rouge

Reputation: 4239

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. Thanks a lot!

Upvotes: -1

Views: 194

Answers (2)

Ganzert
Ganzert

Reputation: 48

If you are trying to target a single element, you should to use 'id':

document.getElementById('id_of_the_element').src = "new_img.png";

Upvotes: 0

Stecman
Stecman

Reputation: 3060

document.getElementsByClassName('button') returns a NodeList, not an element. If you want to add backImg to every element with the class .button you would need to loop through that 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:

document.getElementById('button').appendChild(backImg);

Note that HTML ids must be unique within the document.

Upvotes: 4

Related Questions