Riddhi Rathod Riddhi Rathod - 1 month ago 12
Javascript Question

Can't get effect of "\n" in javascript



function myMap() {
var addrlist = document.getElementById("addresslist");

var jsaddr = "Address Line1 <br /> Address Line 2 <br /> Address Line 3";
var addr = jsaddr.split("<br />");
//alert(addr);
var addrfinal = "";
for(var j=0;j<addr.length;j++)
{
addrfinal = addrfinal + addr[j] + "\n";
}
alert(addrfinal);

var traddr = document.createElement("tr");
var tdaddr = document.createElement("td");
var tdaddress = document.createTextNode(addrfinal);
tdaddr.appendChild(tdaddress);
traddr.appendChild(tdaddr);
addrlist.appendChild(traddr);
}

<table id="addresslist">
</table>
<input type="button" value="Click" onclick="myMap()" />





I want to add address to table line by line. But when I alert string it will get the effect of "\n", but in string I can't get the effect of "\n"

Answer

I want to add address to table line by line.

In that case you are just complicating things. All you need is to use innerHTML property on the td element and assign your initial string.

tdaddr.innerHTML = jsaddr;

Check the example below.

function myMap() {
	var addrlist = document.getElementById("addresslist");

	var jsaddr = "Address Line1 <br /> Address Line 2 <br /> Address Line 3";	    	
  
	var traddr = document.createElement("tr");
	var tdaddr = document.createElement("td");
	
	tdaddr.innerHTML = jsaddr;  // this is the change
	traddr.appendChild(tdaddr);
	addrlist.appendChild(traddr);			
}
<table id="addresslist">
</table>
<input type="button" value="Click" onclick="myMap()" />

Comments