views:

231

answers:

2

i want to escape some HTML in JavaScript. How can I do that?

+1  A: 

You could create a dummy textarea, set its innerHTML to your escaped html [the html with >s] and use the textarea.value

var ta = document.createElement('textarea');
 ta.innerHTML = ">";
 alert(ta.value);

... had to use this on a CMS once [although when i used it, it was bad practice]

ItzWarty
+3  A: 

I often use the following function to decode HTML Entities:

function htmlDecode(input){
  var e = document.createElement('div');
  e.innerHTML = input;
  return e.childNodes[0].nodeValue;
}

htmlDecode('&lt;&gt;'); // "<>"

Simple, cross-browser and works with all the HTML 4 Character Entities.

CMS