yourfriendzak yourfriendzak - 3 months ago 13
HTML Question

Appending HTML-encoded string as HTML, not as text

I'm trying to append this string:

<div> hello </div>


as an HTML node, but instead of appending HTML it just appends the text:

<div> hello </div>


How do I make jQuery append this as an HTML node, not just text?

I'd like a solution that works both for nested divs AND text, if possible.

Answer
// This is your string :)
var myString = "&lt;div&gt; hello &lt;/div&gt;";

// This is a way to "htmlDecode" your string... see link below for details.    
myString = $("<div />").html(myString).text();

// This is appending the html code to your div (which you don't have an ID for :P)
$("#TheDivIWantToChange").append(myString);

HTML-encoding in JavaScript/jQuery

Comments