Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Put a Javascript variable into a innerHTML code

I'm creating a table dynamic table with Javascript:

var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
var cell5 = row.insertCell(4);

I want to fill the cell5 with some innerHTML with a Javascript variable inside

var add = aux[i].split("#");
cell5.innerHTML = "<img src='MatrixLogos/add[3]' width='100' height='25'/>";

but this give add[3] in the html instead of the value inside add[3].

My question is how to escape the variable inside the innerHTML code, so it shows me is value and not the declaration.

like image 827
user1843376 Avatar asked May 09 '13 17:05

user1843376


People also ask

How do I add a variable to innerHTML?

How it works. First, get the <ul> element with the id menu using the getElementById() method. Second, create a new <li> element and add it to the <ul> element using the createElement() and appendChild() methods. Third, get the HTML of the <ul> element using the innerHTML property of the <ul> element.

How do you put a JavaScript variable in HTML?

To add the content of the javascript variable to the html use innerHTML() or create any html tag, add the content of that variable to that created tag and append that tag to the body or any other existing tags in the html.

How do you assign a value to a variable in HTML?

Use the <var> tag in HTML to add a variable. The HTML <var> tag is used to format text in a document. It can include a variable in a mathematical expression.

How do you store variables in HTML?

Answer: Use the concatenation operator (+) The simple and safest way to use the concatenation operator ( + ) to assign or store a bock of HTML code in a JavaScript variable. You should use the single-quotes while stingify the HTML code block, it would make easier to preserve the double-quotes in the actual HTML code.


2 Answers

Use "+".

var add = aux[i].split("#");
cell5.innerHTML = "<img src='MatrixLogos/"+add[3]+"' width='100' height='25'/>";
like image 81
parnas Avatar answered Oct 19 '22 00:10

parnas


Use String concatenation like

var add = aux[i].split("#");
var string = "This is to " + add[3] + " test with value";

Where as in your case, statement will become:

cell5.innerHTML = "<img src='MatrixLogos/"+add[3]+"' width='100' height='25'/>";
like image 25
Kailash Yadav Avatar answered Oct 19 '22 00:10

Kailash Yadav