简体   繁体   中英

Set the src attribute of img tag from an array element

I have an array

pics = ["url1", "url2", "url3"]

I want want to be able to set the src attribute of an image to an array element like so:

<img src = pics[0]>

Problem is that html does not recognize that I am want the string element pic[0] not literally "pic[0]", so it throws an error

Uncaught TypeError: Cannot set property 'src' of null 

Thanks

You can't use JavaScript in arbitrary HTML attributes. You need to modify the DOM to add them afterwards.

 var img = document.createElement('img');
 img.alt = "Suitable alternative text";
 img.src = pics[0];
 document.getElementById('someElement').appendChild(img);

Make sure the script runs after someElement exists so it doesn't error on the last line.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM