-1

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!

0

2 Answers 2

4

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.