Programmatically change the src of an img tag

后端 未结 9 1666
执念已碎
执念已碎 2020-11-22 04:31

How can I change the src attribute of an img tag using javascript?


         


        
9条回答
  •  青春惊慌失措
    2020-11-22 05:16

    With the snippet you provided (and without making assumptions about the parents of the element) you could get a reference to the image with

    document.querySelector('img[name="edit-save"]');
    

    and change the src with

    document.querySelector('img[name="edit-save"]').src = "..."
    

    so you could achieve the desired effect with

    var img = document.querySelector('img[name="edit-save"]');
    img.onclick = function() {
        this.src = "..." // this is the reference to the image itself
    };
    

    otherwise, as other suggested, if you're in control of the code, it's better to assign an id to the image a get a reference with getElementById (since it's the fastest method to retrieve an element)

提交回复
热议问题