Skip to content
Advertisement

JavaScript – capture img tags src in variable

im trying to store an image in HTML that comes from a url source in a variable using JavaScript. Could someone show me what code is required? i have started it off…

 var productImage = document.getElementById("productImg").//??;


<img id="productImg"
                    src="https://i5.walmartimages.com/asr/1735db1c-d84f-417a-b871-27b63ee2b2e6_1.9a18f15c0e0fa321d0c5d073875b9738.jpeg?odnWidth=undefined&odnHeight=undefined&odnBg=ffffff" >

Advertisement

Answer

You can use the src property.

 var productImage = document.getElementById("productImg").src

You can also use the src property to set a new URL for the image if you want to replace it.

 var productImage = document.getElementById("productImg");
     productImage.src = URL
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement