4

I'm trying to set the src attribute of an image to a URL that I also generate in JS. The URL contains several parameters chained with a "&", but when getting the element's outer HTML as string value, all the "&" are replaced by "&amp ;, making the URL useless. Why is this happening? Do I have to replace all the occurencies to fix it?

var img = $("<img>");
img.attr("src","/test?param1=1&param2=2");
console.log(img[0].outerHTML); //printing <img src="/test?param1=1&amp;param2=2">

getting the src attribute from that object shows the original string so I believe the value is encoded when accessing outerHTML.

user1563232
  • 361
  • 3
  • 17

1 Answers1

0

This is just the result of logging the img using outerHTML, because that function serialises strings before they are output. In the example below I am just logging the element and you will see the image source is correct. Also if you output the image on the page it also has the correct source.

So there is nothing wrong with your code other than the way you are logging the output.

var img = $("<img>");
img.attr("src","http://www.placecage.com/gif/284/196?param1=1&param2=2");
console.log(img[0]);
$("div").append(img);
<div></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
WizardCoder
  • 3,353
  • 9
  • 20
  • Ok you're right I found the problem elsewhere. It gets serialised because I'm setting a textboxes content with text(), so the HTML code can be copied. Is there another way to show plain HTML code without changing its contents? – user1563232 Jun 17 '17 at 16:10