Take the 2-minute tour ×

When I add HTML to a div element and later try to get it back, jQuery either removes the HTML tags or converts all applicable characters to HTML entities, depending on if I use .html() or .text().

Here's a demonstration (jsfiddle)

$('div').html('<h1>Hi, Alice & Bob</h1>');
console.log('html: ' + $('div').html());
console.log('text: ' + $('div').text());

Console output

html: <h1>Hi, Alice &amp; Bob</h1>
text: Hi, Alice & Bob 

How do I get back exactly <h1>Hi, Alice & Bob</h1>?

share|improve this question
Why not innerHTML ? –  FSou1 Jul 27 '13 at 0:36
@FSou1 As you can see in the jQuery source code, .html() is based on innerHTML. I have, however, updated the jsfiddle to demonstrate innerHTML. –  kba Jul 27 '13 at 0:43

1 Answer 1

up vote 0 down vote accepted

I don't know any other way to solve this other than to decode the entities like so

var decode = function( val ) {
  var el  = document.createElement('textarea');
      el.innerHTML = val;
  return el.value;

Here is a function that will do that for you

and usage like this

console.log( decode( $('div').html() ) );
// Result is => <h1>Hi, Alice & Bob</h1> 


share|improve this answer
Thank you for your answer. That does solve the actual example, but try with a string like <h1>Hi, Alice & Bob &hellip;</h1>. –  kba Jul 27 '13 at 1:00
I'm working on it. –  Connor Jul 27 '13 at 1:08
You may wan't to check here for hellip stackoverflow.com/questions/1417818/html-entities-with-jquery –  Connor Jul 27 '13 at 1:11

Your Answer


