Presenting HTML as text is a common task, but surprisingly there isn't a lot of info on how to do it properly (read: securely). I'm no security expert, so I didn't want the responsibility of writing my own sanitizing function or trusting one on the web. Luckily, the browser can do this for us, and with jQuery, it's even easier: you can
use .text(), which in turn uses the DOM method .createTextNode(). You just need a placeholder element, like a , and call the .text() after it's rendered.
I use the jQuery plugin
DataTables whenever I want standard table functionality, like pagination, sorting, etc. It's a little more complicated to use the .text() technique here, but not much.
Say we have data that might contain HTML in an array called htmlText. Here's how I might sanitize & display it in a DataTable (omitting other columns):
var tableData = []; // data to be displayed by DataTable
for (var i = 0; i < htmlText; i++) {
// placeholder span element with id "dt"
// we use the "dt" prefix as a sort of namespace
tableData.push(['']);
}
$(selector).dataTable({
aaData: tableData,
aoColumns: [{ sTitle: 'HTML' }],
fnDrawCallback: function() {
$("span.htmltext").each(function () {
// get array index of each , slicing off the "dt", and
// insert the value from the array
$(this).text(htmlText[$(this).attr("id").slice(2)]);
});
}
});