Abhijeet Panwar
Abhijeet Panwar

Reputation: 1867

Text in dynamically generated links appears after end tag

I am generating a link dynamically using jQuery by iterating some Json data.

MyCode :

var content = "<table>";
$.each(dataArray, function( index, value )
{
     content = content+"<tr><td>"+value.Version+"</td><td><a href="+value.Download+"> Download</a></td></tr>";
}); 
content = content+"</table>";
$('#tablediv').append(content);

It should generate a table with a link in 2nd colum as:

< a href="link to url"> Download < /a>

But it generates it as :

< a href="link to url">< /a> Download

So I need text between start and end tag but it appears after end tag. How to resolve this issue?

Upvotes: 0

Views: 47

Answers (4)

HGrover
HGrover

Reputation: 225

$(document).ready(function(){
var content = "<table>";
  var dataArray=[{Version:1,Download:"asdsa"},{Version:2,Download:"tete"}];
$.each(dataArray, function( index, value )
{
  var $row=$("<tr>");
  var $rowcellVersion= $("<td>").text(value.Version);
  var $rowcellContent= $("<td>");
  var $anchorTag = $("<a>").text("Download")
                           .attr("href",value.Download)  
                           .appendTo($rowcellContent);
  
  $rowcellVersion.appendTo($row);
  $rowcellContent.appendTo($row);
  
  content = content + $row[0].outerHTML;
  
}); 
content = content+"</table>";
$('#tablediv').append(content);
  
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="tablediv"></div>

A bit cleaner way of handling the creation of elements .Also you can check the HTML in page inspector .It's the expected way

Upvotes: 1

Vojtech B
Vojtech B

Reputation: 2957

You can leverage jQuery if you are using it in a first place

var content = $("<table>");
$.each(dataArray, function( index, value )
{
  content.append($("<tr />")
     .append($("<td />").text(value.Version))
     .append($("<td />").append(
              $("<a />").attr("href",value.Download).text(value.Version))
);
$('#tablediv').append(content);

Upvotes: 0

brroshan
brroshan

Reputation: 1650

You need to add single-quotes to your href attribute.

content += "<tr><td>"+value.Version+"</td><td><a href='"+value.Download+"'> Download</a></td></tr>";

Upvotes: 2

billyonecan
billyonecan

Reputation: 20260

You need to wrap value.Download in quotes:

"... <a href=\"" + value.Download + "\">Download</a> ...";

Upvotes: 1

Related Questions