Mike D
Mike D

Reputation: 2841

escaping html markup

I'm building a html table using javascript on the fly and I want to add a cell that may contain html markup. I do not want that markup interpreted but simply displayed.

  LogHTML += "<tr><td>" + data + "</td></tr>";

How can I do that? Is there some function or html markup that will accomplish that?

I tried pre but then I get extra spaces.

Upvotes: 0

Views: 912

Answers (2)

artyom.stv
artyom.stv

Reputation: 2164

The best solution is to use DOM instead of innerHTML and to create text node for data.

But you can try this as a quick solution or

function htmlentities(s){
    var div = document.createElement('div');
    var text = document.createTextNode(s);
    div.appendChild(text);
    return div.innerHTML;
}

Upvotes: 1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324840

LogHTML += "<tr><td>"+data.replace(/</g,"&lt;")+"</td></tr>";

That's all you need.

Upvotes: 1

Related Questions