1

if i type this:

test.innerHTML += "<img src=./images/pink.JPG>"+"<label> <input type='radio' name='choices' value='A'></label>";

i am able to display the image pink. However how would i do this by using a variable i.e picture = "pink.JPG"

i have tried

test.innerHTML += "<img src=./images/' + picture + '>"+"<label> <input type='radio' name='choices' value='A'></label>";

however it doesn't work. What would be the correct way?

j08691
  • 204,283
  • 31
  • 260
  • 272
Bea
  • 11
  • 2

3 Answers3

1

We use back-ticks now ` in ES6. If you use these you no longer need to worry about anything else. Just try this:

test.innerHTML += `<img src="./images/pink.JPG"><label><input type="radio" name="choices" value="A"></label>`;

This will also help in using a dynamic data or url being added in your code (String Interpolation) using ${srcUrl} This is freaking easy to use as well.

Imran Rafiq Rather
  • 7,677
  • 1
  • 16
  • 35
  • @Bea: Hope this is the best and easy approach so far. You can learn more about this from ES6 string interpolation topic. Do please rate and accept my answer for other's to benefit from this as well. Thank you mate :) – Imran Rafiq Rather Dec 14 '20 at 20:55
0

The key is using the same quotes that you are wrapping the string with, in this case it is double quotes.

test.innerHTML += "<img src='./images/" + picture + "'><label> <input type='radio' name='choices' value='A'></label>";
imvain2
  • 15,480
  • 1
  • 16
  • 21
0

You need to use " instead of ' So your code wood look like this:

test.innerHTML += "<img src=\"./images/" + picture + "\">"+"<label> <input type='radio' name='choices' value='A'></label>"

And if you still want to use " for "hugging" an attribute, you can use \"

MoPaMo
  • 517
  • 6
  • 24