loriensleafs
loriensleafs

Reputation: 2255

using variable in prepend img src

I have a img source I'm trying to prepend but I'm trying to use the variable "id" in the source. I'm having trouble modifying this snippet of code to do that.

  $('#photo_850').prepend('<img src= id + ".jpg" />');

thanks for helping me with this

Upvotes: 3

Views: 2048

Answers (1)

Sampson
Sampson

Reputation: 268374

Your concatenation was off:

$('#photo_850').prepend('<img src="'+id+'.jpg" />');

Another, perhaps easier to read, method would be:

$("<img>", { src: id + ".jpg" }).prependTo("#photo_850");

This method first creates the element represented by a string in the first parameter. Next, jQuery proceeds to map the members of the object literal to the newly-created HTML element. You can probably guess by now that our newly-created <img> will have a src property of foo.jpg, assuming the variable id is a string of "foo".

Upvotes: 6

Related Questions