0

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

user1452494
  • 1,145
  • 5
  • 18
  • 40

1 Answers1

3

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • 1
    I don't know about that.. pretty sure if it has something taht can uniquely identify it.. `` you can modify it by doing `document.getElementById('somelink').src = pics[0];` - though i haven't tried it. – ddavison Jan 13 '14 at 15:34
  • There is no sign of there being an *initial* value for the (mandatory) `src` that doesn't come from JS, so the entire element should be created with JS. – Quentin Jan 13 '14 at 15:35
  • what do you mean by the script should run after someElement? – user1452494 Jan 13 '14 at 15:39
  • I said "after someElement exists". If you run it before the element exists, then it will get `null` when `document.getElementById('someElement')` and then error when it tries to `null.appendChild(img);`. You need to put the script after that element, or in a function that isn't called until that element exists. – Quentin Jan 13 '14 at 15:43
  • it works, just need to fiddle with CSS to make the image actually show up. Now it doesnt throw an error, but its just an empty box – user1452494 Jan 13 '14 at 15:57