Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 591
zakdances Avatar asked Dec 08 '11 20:12

zakdances


People also ask

What is HTML encoded string?

HTML encoding ensures that text will be correctly displayed in the browser, not interpreted by the browser as HTML. For example, if a text string contains a less than sign (<) or greater than sign (>), the browser would interpret these characters as an opening or closing bracket of an HTML tag.

Should I encode HTML?

You should always specify the encoding used for an HTML or XML page. If you don't, you risk that characters in your content are incorrectly interpreted. This is not just an issue of human readability, increasingly machines need to understand your data too.


1 Answers

// 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 lost when attribute read from input field

like image 111
Timothy Khouri Avatar answered Oct 13 '22 02:10

Timothy Khouri