1

I have strings of HTML formatted text in a database, e.g:

<div><p>example</p></div>

And I'm adding them to fields in a table. The table html is created in a string and appended to a div with jQuery like this:

var str = '<table><thead><tr><th>Heading</th></tr></thead><tbody>';
str += '<tr><td>';
str += database[index].fieldWithHtml;
str += '</td></tr></tbody></table>';

$("#myElement").append(str);

Currently the text that shows in the cell is formatted and shows just 'example'. What I want is for it to not actually use the html tags to format the text, but rather to show them, e.g. the example output would be the same:

<div><p>example</p></div>
Lukesmith
  • 170
  • 2
  • 16
  • 3
    Escape the string from database depending on your server side language. Like htmlspecialchars for PHP. http://php.net/manual/de/function.htmlspecialchars.php and http://php.net/manual/de/function.htmlentities.php – Tyr Dec 27 '14 at 15:53
  • If you've to ask this, I'm just thinking (with horror) the code how you've actually stored the strings to the database? – Teemu Dec 27 '14 at 15:56
  • The answer is here http://stackoverflow.com/questions/1787322/htmlspecialchars-equivalent-in-javascript – Adam Cherti Dec 27 '14 at 15:57

1 Answers1

2

Use jQuery functions to create DOM elements, and put the literal text into the text of the <td>.

var table = $("<table><thead><tr><th>Heading</th></tr></thead><tbody>");
var row = $("<tr>").append($("<td>", { text: database[index].fieldWithHtml}));
$("tbody", table).append(row);
$("#myElement").append(table);
Barmar
  • 741,623
  • 53
  • 500
  • 612