Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 971
loriensleafs Avatar asked Nov 30 '25 02:11

loriensleafs


1 Answers

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".

like image 197
Sampson Avatar answered Dec 02 '25 15:12

Sampson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!