8

I'm trying to build a HTML string in the following way:

htmlString = '<html>';
var headerString = "image1";
var sImage = "Android_images/"+headerString+".png";
htmlString += '<img src='+sImage+' />';
htmlString = '</html>';

I need to dynamically append a image string, but it shows:

<img src=Android_images/dfdfd.png />
vishnu
  • 405
  • 2
  • 10
  • 17

6 Answers6

8

You're re-setting the variable on this last line:

htmlString = '</html>';

Add a + and it'll work:

var htmlString = '<html>';
var headerString = "image1";
var sImage = "Android_images/" + headerString + ".png";
htmlString += '<img src="' + sImage + '" />';
htmlString += '</html>';

Also, why are there <html> tags here?

Blender
  • 289,723
  • 53
  • 439
  • 496
2

Try:

var htmlString = '<html>';
var headerString = "image1";
var sImage = "Android_images/"+headerString+".png";
htmlString += '<img src="'+sImage+'" />';
htmlString += '</html>';
MervS
  • 5,724
  • 3
  • 23
  • 37
0
var htmlString = '<html>';

htmlString += '</hmtl>';
0

You haven't defined htmlString as a variable before you started using it:

var htmlString = '<html>';
Borniet
  • 3,544
  • 4
  • 24
  • 33
0

you should always use var.

Not using var has two major drawbacks:

  • Accessing a variable within a function that is not defined within that function will cause the interpreter to look up the scope chain for a variable with that name until either it find one or it gets to the global object (accessible in browsers via window) where it will create a property. This global property is now available everywhere, potentially causing confusion and hard-to-detect bugs;
  • Accessing an undeclared variable will cause an error in ECMAScript 5 strict mode.

Working Perfectly here and in last line you should use +=:

htmlString += '</html>';
Zaheer Ahmed
  • 28,160
  • 11
  • 74
  • 110
0

use below code

var htmlString = '<html>';
var headerString = "image1";
var sImage = "Android_images/"+headerString+".png";
htmlString += '<img src="'+sImage+'" />';
htmlString += '</html>';

"htmlString" will contain below output

<html><img src="Android_images/image1.png" /></html>

think it will help you.

Ripa Saha
  • 2,532
  • 6
  • 27
  • 51