2

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>?

2
  • Why not innerHTML ? Commented Jul 27, 2013 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. Commented Jul 27, 2013 at 0:43

1 Answer 1

0

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

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

Demo

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your answer. That does solve the actual example, but try with a string like <h1>Hi, Alice & Bob &hellip;</h1>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.