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

2
  • How are you selecting the picture, can you post that javascript? Commented Jan 13, 2014 at 15:30
  • need more details, please post your code Commented Jan 13, 2014 at 15:32

1 Answer 1

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.

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

5 Comments

I don't know about that.. pretty sure if it has something taht can uniquely identify it.. <img id="somelink" src=""> you can modify it by doing document.getElementById('somelink').src = pics[0]; - though i haven't tried it.
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.
what do you mean by the script should run after someElement?
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.
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

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.